DataGridColumnHeader中的WPF绑定DataTemplate [英] WPF Binding in DataGridColumnHeader DataTemplate
问题描述
因此,这是以下问题的扩展:样式DataGridColumnHeader中的样式在WPF
So, this is an extension to the following question: Style DataGridColumnHeader with Styles in WPF
简而言之,我试图通过使用组合框对列标题进行模板,将过滤器放在DataGridColumnHeaders中。所以与另一个例子的区别是我正在使用ComboBoxes。
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>
我的问题与绑定ComboBox到一些值。我现在遇到将ItemsSource绑定到ViewModel中的一个属性的问题,如上所示,但是我无法让它工作。我的第二个问题是如何修改代码,以便每列可以绑定到不同的值?
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??
推荐答案
code> DataGridColumnHeaders 不继承 DataContext
,所以他们没有任何约束力。使用 RelativeSource
在绑定中查找父代 DataGrid
,并指向 DataContext.Codes
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>
这篇关于DataGridColumnHeader中的WPF绑定DataTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!