开发者

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

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 sensibl开发者_JS百科e workaround?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜