All DataGrid headers must have unique names - how to work around it

拟墨画扇 提交于 2020-01-16 14:39:13

问题


I am using a DataGrid with AutogenerateColumns set to true.

I'm binding it to a weakly-typed DataTable via its DataContext property.

The problem I've run into is that all the headers must have unique names, because myGrid.Columns[x].Header value is tied directly to the column name of the underlying DataTable (where, obviously, no duplicate column names are allowed).

Is there any sensible workaround?


回答1:


Following code is untested...

For DataGridHeaders to be changed, you would have to override their 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>

In the above code DynamicColumnHeaderTextConverter's Convert() method will receive 2 values

  1. Column Header i.e. DataTable Column Name
  2. DataTable itself.

Based on this return the non-unique names.

    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; 
         }
    }

Let me know if this helps.



来源:https://stackoverflow.com/questions/6928393/all-datagrid-headers-must-have-unique-names-how-to-work-around-it

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