问题
I am creating a customized listview header that has the header text but also has a textbox that you can enter to filter the content of that column. My code currently looks like this:
<UserControl.Resources>
<DataTemplate x:Key="myHeaderTemplate">
<StackPanel>
<TextBlock FontSize="14" Foreground="DarkBlue" Margin="20,4" Text="{Binding}" />
<TextBox Text="" Margin="4,2" />
</StackPanel>
</DataTemplate>
</UserControl.Resources>
which is the definition for the header datatemplate containing the texbox; and the listview
<ListView ItemsSource="{Binding Path=MyData}" IsSynchronizedWithCurrentItem="True">
<ListView.View>
<GridView>
<GridViewColumn Header="Last Name" HeaderTemplate="{StaticResource myHeaderTemplate}"
DisplayMemberBinding="{Binding Path=Something}" />
<GridViewColumn Header="First Name" HeaderTemplate="{StaticResource myHeaderTemplate}"
DisplayMemberBinding="{Binding Path=Something}" />
<GridViewColumn Header="Address" HeaderTemplate="{StaticResource myHeaderTemplate}"
DisplayMemberBinding="{Binding Path=Tube}" />
</GridView>
</ListView.View>
</ListView>
I want to be able to build up a filter statement that I can apply to the listview rows, but to do that I have to get the data from each filter textbox in the header template.
Can I somehow bind the textboxes in the headers to properties on my viewmodel? If not is there some other way to get the text?
Thanks for any help.
回答1:
You should be able to bind the header to a property like this:
<GridViewColumn
Header="{Binding LastNameFilter, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}}"
HeaderTemplate="{StaticResource myHeaderTemplate}"
DisplayMemberBinding="{Binding Path=Something}" />
The RelativeSource
is needed to get to the DataContext
of the ListView
- you could also give it a name and use ElementName
instead.
Now you can make a HeaderFilter
class:
public class HeaderFilter
{
public string Name { get; set; }
public string Filter { get; set; }
}
Obviously you would need to extend that class to hook into the event when Filter
is changed to perform the filtering.
Put a property for each column header on the object which is the DataContext
for your ListView
(same object which provides MyData
probably)
public class SomeClass
{
....
public HeaderFilter LastNameFilter { get; set; }
....
}
来源:https://stackoverflow.com/questions/5610190/binding-textbox-in-listviews-header-datatemplate-to-a-filter-property