Question

I have an ObservableCollection<MyClass> named myCollection that should be binded to two CollectionViewSources (AllItems and SelectedItems).

AllItems's source property is binded to the myCollection. SelectedItems's source property should be bind to myCollection items which IsSelected == true.

public class MyClass : INotifyPropertyChanged
{
    //fields and interface implementations
    public string Name {//proper code};
    public bool? IsSelected {//proper code};
}

// some where else in the MainWindow
AllItems.Source = myCollection;
SelectedItems.Source = myCollection.Where(input=>input.IsSelected==true);

Problem: Every thing is OK when the Window is loaded. But when the IsSelected value for some items in the myCollection is changed obviously it has no effect on the SelectedItems. So to overcome this problem I update the source property of the SelectedItems every time an IsSelected property is changed.

Question: How can I do these kind of binding so that there is no need to manually update the source property of the SelectedItems?

Thnaks.

Was it helpful?

Solution

First of all, you should unconditionally remove your manual filtering setup and replace it with something more appropriate. The choice of what to replace with depends mainly on what .NET version you are targeting.

If targeting .NET 4.5 then a simple solution is and instead enable live filtering on the collection view.

For earlier versions of .NET you will have to do some manual work no matter what, but it is better to just call Refresh on the collection view that re-bind your control. To do this, you should defer the filtering to the collection view itself by setting the Filter event handler from XAML.

OTHER TIPS

After the changes in MyClass you should raise PropertyChanged Event.

If you already do this than you should look at your SelectedItems.Source in Debug mode. Maybe its the correct value already there but its not shown to you.

I mean if SelectedItems.Source belongs to some visible Elements - GUI - you should refresh it on the screen. Cause the other way the value is there but will not be shown till your Element on the Screen is repainted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top