I have multiple DataGrid objects in different tabs of WPF window that share the same columns.
I can define a column as a resource like this:
<TabControl.Resources>
<DataGridTextColumn x:Key="NameGridColumn" Binding="{Binding Name}" IsReadOnly="True" Width="*">
<DataGridTextColumn.Header>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Name" VerticalAlignment="Center"/>
<Button Command="{Binding SortByNameCommand}" Content="▲" Background="Transparent" BorderThickness="0" Margin="5 0 0 0"/>
</StackPanel>
</DataGridTextColumn.Header>
</DataGridTextColumn>
</TabControl.Resources>
But how can I then use these resource columns in a DataGrid?
<TabItem Header="Tab 1">
<DataGrid ItemsSource="{Binding ItemsCollection}" CanUserAddRows="False" CanUserDeleteRows="False" CanUserSortColumns="False" AutoGenerateColumns="False">
<DataGrid.Columns>
<????>
<!-- notice that I have many columns, not just one -->
</DataGrid.Columns>
</DataGrid>
</TabItem>
Not the ideal answer, but fairly good.
This is an answer specific for data grid column headers (the columns you define are not actual controls, but representations for controls that will be generated later). If you want an answer for actual controls in general, you can resort to this answer
You can use a
DataTemplateto define the headers:And you can use the
HeaderTemplateproperty of aDataGridTextColumnor aDataGridTemplateColumn.The downsides are:
DataGridTemplateColumn'sCellTemplateorCellEditingTemplate) or styles if it's the caseRelativeSourceset to some element above it