Binding a property inside a CollectionViewSource to a ViewModel property

I am here with a new problem.

I have a DataGrid and TextBox. I would like to filter the DataGrid based on the value of the TextBox.

I did this using MarkupExtensions , as mentioned here .

Now it works fine up to the Value property (property of the PropertyFilter class, as indicated in the link above) - this is the string specified in XAML. When I change it to a binding, it stops working. Here is my binding XAML:

 <CollectionViewSource x:Key="GroupsViewSource" Source="{Binding Groups}"> <CollectionViewSource.Filter> <me:Filter> <me:PropertyFilter PropertyName="GroupName" Value="{Binding SearchGroupName}" /> </me:Filter> </CollectionViewSource.Filter> </CollectionViewSource> 

SearchGroupName is a simple property of type string in my ViewModel.

I also tried changing the binding as follows:

 Value = "{Binding DataContext.SearchGroupName, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}" 

I tried to debug it using System.Diagnostics as follows:

 <CollectionViewSource x:Key="GroupsViewSource" Source="{Binding Groups}"> <CollectionViewSource.Filter> <me:Filter> <me:PropertyFilter PropertyName="GroupName" Value="{Binding SearchGroupName, diag:PresentationTraceSources.TraceLevel=High}" /> </me:Filter> </CollectionViewSource.Filter> </CollectionViewSource> 

But then I get a compilation error: unknown property PresentationTraceSources.TraceLevel for System.Windows.Data.Binding ......

I think my binding to RelativeSource does not work, because I believe that CollectionViewSource is not a member of the Visual / Logical Tree.

So, I think my DataContext could be null. What solutions do you prefer if you are in the same situation ?????

0
c # data-binding wpf xaml
source share
1 answer

You can try moving the filter to the resources of the framework element with the correct DataContext using a binding, for example Path=DataContext.<property-name>, Source={x:Reference <element-name>} . Link to the filter where you need it using StaticResource .

This workaround is useful for binding in containers for a collection , for example.


The code should be something like this (untested):

 <SomeElement Name="el"> <SomeElement.Resources> <me:PropertyFilter x:Key="Filter1" PropertyName="GroupName" Value="{Binding DataContext.SearchGroupName, Source={x:Reference el}}" /> <CollectionViewSource x:Key="GroupsViewSource" Source="{Binding Groups}"> <CollectionViewSource.Filter> <me:Filter> <StaticResource ResourceKey="Filter1"/> </me:Filter> </CollectionViewSource.Filter> </CollectionViewSource> 
+1
source share

All Articles