【问题标题】:All DataGrid headers must have unique names - how to work around it所有 DataGrid 标头都必须具有唯一的名称 - 如何解决它
【发布时间】:2011-10-19 04:40:12
【问题描述】:

我正在使用 DataGrid 并将 AutogenerateColumns 设置为 true

我通过其DataContext 属性将其绑定到弱类型DataTable

我遇到的问题是所有标题都必须具有唯一的名称,因为myGrid.Columns[x].Header 值直接绑定到底层DataTable 的列名(显然,不允许重复的列名) .

有什么合理的解决方法吗?

【问题讨论】:

  • 您能否详细说明您的问题? DataTable 不是在做你想做的事(列名的唯一性)吗?
  • 我想在DataGrid 中有非唯一的标题 - 显示名称;在用户界面中!不影响DataTable 中的列名(这会导致抛出异常)。我根本不希望(可见)标题名称与(逻辑)列名连接;但截至目前,他们是。

标签: .net wpf data-binding datagrid datatable


【解决方案1】:

以下代码未经测试...

要更改 DataGridHeaders,您必须覆盖其 ContentTemplate。

    <DataGrid.Resources>   
     <Style TargetType="{x:Type dg:DataGridColumnHeader}">
      <Setter Property="ContentTemplate">
         <Setter.Value>
            <DataTemplate>
               <StackPanel>
                   <TextBlock>
                      <TextBlock.Text>
                          <MultiBinding Converter="{StaticResource DynamicColumnHeaderTextConverter}">
                               <Binding BindsDirectlyToSource="True"/>
                               <Binding Path="ItemsSource" RelativeSource="{RelativeSource AncestorType={x:Type dg:DataGrid}}" />
                          </MultiBinding>
                      </TextBlock.Text>
                   </TextBlock> 
               </StackPanel>
           </DataTemplate>
         </Setter.Value>
      </Setter>
     </Style>
    </DataGrid.Resources>

上面代码中DynamicColumnHeaderTextConverter的Convert()方法会收到2个值

  1. 列标题,即数据表列名
  2. 数据表本身。

基于此返回非唯一名称。

    public class DynamicColumnHeaderTextConverter : IMultiValueConverter
    {
         public object Convert(object[] values, ...)
         {
              var columnName = (string)values[0];
              var dataTable = (DataTable)values[1]; //// if you want to decide name based on some value in the DataTable.
              switch(columnName)
              {
                   case "MyColumn1" : return "MyColumn";
                   case "MyColumn2" : return "MyColumn";
              }

              return columnName; 
         }
    }

如果这有帮助,请告诉我。

【讨论】:

  • 谢谢!明天我会试试这个(我今天差不多完成了:))。顺便说一句,我已经覆盖了DataGridColumnHeaderContentTemplate,所以我将合并您提出的代码。我会告诉你的
  • 我试过了,但不幸的是它不起作用。我收到 XamlParseException:“不能在 'Binding' 类型的 'Path' 属性上设置 'Binding'。只能在 DependencyObject 的 DependencyProperty 上设置'Binding'。”
  • 嘿 Vibo,抱歉代码错误... 应该是 ... 我已经在上面编辑了我的代码... 再次为您带来麻烦!
  • 谢谢 - 但它也不起作用。我现在在家里用你更新的示例代码创建了一个小项目,我又遇到了同样的异常:不能在“Binding”类型的“Path”属性上设置“Binding”。只能在 DependencyObject 的 DependencyProperty 上设置“绑定”。
  • 我确定我做错了什么,但我不知道它是什么。我会继续努力的。
猜你喜欢
  • 1970-01-01
  • 2023-03-23
  • 2023-03-16
  • 2021-05-29
  • 2015-10-11
  • 2013-09-13
  • 1970-01-01
  • 1970-01-01
  • 2017-09-13
相关资源
最近更新 更多