WPF Binding to collection with constraint
I have an observable collection of objects. I wish to bind a gridview to this observable collection. But there is a constraint that only objects whose property x has value a, must be binded
How to do that?
I got it working using CollectionView and filter. For others benefit the code is as follows
Solution :
public class CustomerViewModel
{
public ObservableCollection<Customer> Customers
{
get;
set;
}
priva开发者_StackOverflowte ICollectionView _filteredCustomerView;
public ICollectionView FilteredCustomers
{
get { return _filteredCustomerView; }
}
public CustomerViewModel()
{
this.Customers= new ObservableCollection<Customer>();
Customers= GetCustomer();
_filteredCustomerView= CollectionViewSource.GetDefaultView(Customers);
_filteredCustomerView.Filter = MyCustomFilter;
}
private bool MyCustomFilter(object item)
{
Customer cust = item as Customer;
return (cust.Location == "someValue");
}
}
You should use filtering
I prefer using LINQ.
var result = YourCollection.Where(p => p.x.HasValue).ToObservableCollection();
But you should write your own extension to convert to ObservableCollection.
public static ObservableCollection<T> ToObservableCollection<T>
(this IEnumerable<T> source)
{
if (source == null)
throw new ArgumentNullException("source");
return new ObservableCollection<T>(source);
}
Good luck!
I think you could achieve this in XAML by putting a DataTrigger on the style of your GridView. Something like this:
<DataGrid>
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridRow}">
<DataTrigger Binding="{Binding IsFiltered}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding IsFiltered}" Value="False">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style>
</DataGrid.Resources>
</DataGrid>
精彩评论