1
votes

So, this is an extension to the following question: Style DataGridColumnHeader with Styles in WPF

In short, I'm trying to put filters in my DataGridColumnHeaders by templating the column headers with a combobox. So the difference with the other example is that I'm using ComboBoxes instead.

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="300" Width="300" Loaded="Window_Loaded">
<Window.Resources>
    <DataTemplate x:Key="MySpecialHeaderTemplate">
        <ComboBox ItemsSource="{Binding Codes}" />
    </DataTemplate>
</Window.Resources>
<Grid>
    <DataGrid>
        <DataGrid.Columns>
            <DataGridTextColumn
                    Binding="{Binding Id}" />
            <DataGridTextColumn HeaderTemplate="{StaticResource MySpecialHeaderTemplate}"
                    Binding="{Binding Name}" />
            <DataGridTextColumn HeaderTemplate="{StaticResource MySpecialHeaderTemplate}"
                    Binding="{Binding Age}" />
        </DataGrid.Columns>
    </DataGrid>
</Grid>

My question pertains to binding the ComboBox to some values. I'm currently having issues with binding the ItemsSource to a property in my ViewModel as shown above, but I can't get it to work. My second question would be how would I alter the code so that I could bind to different values per column??

1
What are the binding errors in the output window? Where do you set the DataContext?H.B.

1 Answers

1
votes

The DataGridColumnHeaders doesn't inherit the DataContext so they have nothing to bind against. Use RelativeSource to find the parent DataGrid in the binding instead and point to DataContext.Codes

<DataTemplate x:Key="MySpecialHeaderTemplate">
    <ComboBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}},
                                    Path=DataContext.Codes}" />
</DataTemplate>