I am trying to build a datagrid where you can filter a column data from a header textbox. I have found some tutorials but they all sound too complicated for what I want to achieve. Furthermore, I want to be able to reuse this FilterDataGrid control in other projects so I thought about creating a custom control.
I think I am pretty close : I can display my textbox in the header while keeping the basic datagrid binding. All I need now is to be able to get the value in my header textbox and use it to filter data in Itemssource.
Here is what I got so far:
FilterDataGrid.cs
using System.Windows;
using System.Windows.Controls;
namespace CustomControlTest
{
public class FilterDataGrid : DataGrid
{
static FilterDataGrid()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(FilterDataGrid), new FrameworkPropertyMetadata(typeof(FilterDataGrid)));
}
public void HeaderFilterTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
// Filter data source from input text.
}
}
}
Generic.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CustomControlTest">
<Style TargetType="{x:Type local:FilterDataGrid}" BasedOn="{StaticResource {x:Type DataGrid}}">
<Style.Resources>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding}"></TextBlock>
<TextBox x:Name="HeaderFilterTextBox" TextChanged="HeaderFilterTextBox_TextChanged"></TextBox>
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</Style.Resources>
</Style>
</ResourceDictionary>
My problem is that I get an error in HeaderFilterTextBox's TextChanged handler :
Error 1 The event 'TextChanged' cannot be specified on a Target tag in a Style. Use an EventSetter instead.
I have no idea how to call this handler in Generic.xaml. If I can do this, the filtering itself should not be too complicated.
Any clue?