WPF Binding in DataGridColumnHeader DataTemplate

邮差的信 提交于 2019-12-24 12:14:30

问题


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:


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>


来源:https://stackoverflow.com/questions/7087299/wpf-binding-in-datagridcolumnheader-datatemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!