Home > Enterprise >  WPF Loose binding when filtering a list
WPF Loose binding when filtering a list

Time:04-11

I have a list of users below:

public ObservableCollection<User> Users
   {
     get;
     private set;
   }

And in the XAML file, I am binding Users to the grid control

<dxg:GridControl x:Name="grid" 
     ItemsSource="{Binding Users}"
     SelectedItem="{Binding CurrentUser}"
     ...
     >
    <dxg:GridControl.Columns>
        <dxg:GridColumn FieldName="Name" Header="name" />
        <dxg:GridColumn FieldName="Mobile" Header="mobile"/>
    </dxg:GridControl.Columns>
</dxg:GridControl>

Until here everything is Ok and the binding works correctly.

Now I want to bind special users. for example, users where the length of their names is less than 5.

private ObservableCollection<TUserItem> usersVisible;
public ObservableCollection<User> UsersVisible
   {
       get
       {
           return Users.Where(u => u.name.Length < 5).ToObservableCollection();
       }

       set
       {
           usersVisible = value;
           OnPropertyChanged();
       }
}

but it doesn't work and the XAML grid control doesn't update.

If I return

return Users;

instead of

return Users.Where(u => u.name.Length < 5).ToObservableCollection();

everything is ok and the binding works correctly.

What's your suggestion?

Thanks

CodePudding user response:

If you look up the source code of the method ToObservableCollection, you will find out that it returns a new collection. So your binding now points to the old objects still and you will not see any change. I have created a repo of a WPF sample for you that you can run here: UI of filtered collection

Note that I have not used an observable collection, but a plain list. You can see a sample of an observable collection using collection view source in this answer on SO: Binding a CollectionViewSource to ObservableCollection

  • Related