开发者

WPF Binding in DataGridColumnHeader DataTemplate

开发者 https://www.devze.com 2023-03-29 02:27 出处:网络
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 wit

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 w开发者_运维技巧ork. My second question would be how would I alter the code so that I could bind to different values per column??


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号