【问题标题】:WPF Binding in DataGridColumnHeader DataTemplateDataGridColumnHeader DataTemplate 中的 WPF 绑定
【发布时间】:2011-08-17 02:18:25
【问题描述】:

所以,这是对以下问题的扩展:Style DataGridColumnHeader with Styles in WPF

简而言之,我试图通过使用组合框对列标题进行模板化来将过滤器放入我的 DataGridColumnHeaders 中。所以与另一个示例的不同之处在于我使用的是 ComboBoxes。

<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 中的属性时遇到问题,如上所示,但我无法让它工作。我的第二个问题是如何更改代码以便我可以绑定到每列的不同值??

【问题讨论】:

  • 输出窗口中的绑定错误是什么?你在哪里设置 DataContext?

标签: wpf templates xaml data-binding datagrid


【解决方案1】:

DataGridColumnHeaders 不继承DataContext,因此它们没有可绑定的对象。使用RelativeSource 在绑定中查找父DataGrid 并指向DataContext.Codes

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

【讨论】:

  • 谢谢!这解决了我问题的第一部分。您可以帮助绑定到我的数据网格中每列的不同集合吗?我现在正在玩它......
  • 谢谢。对于我的第二个问题,我认为我必须为每列定义标题模板,而不是使用共享资源。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-29
  • 1970-01-01
  • 2015-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-17
相关资源
最近更新 更多