Reputation: 545
I tried to apply style for DataGrid globally as followed:
<Style TargetType="DataGrid">
<Setter Property="ColumnWidth" Value="*"/>
<Setter Property="RowHeaderWidth" Value="0"/>
</Style>
The style for RowHeaderWidth
works but the style for ColumnWidth
does not (there is empty column at the end of the DataGrid). When I set ColumnWidth="*"
explicitly in the DataGrid, then it works (the empty column has gone).
I wonder if we are able to set ColumnWidth="*"
globally in the Style? Thank you in advance!
Upvotes: 3
Views: 837
Reputation: 11957
The ColumnWidth setter works for autogenerated columns, but not manually defined ones. Seems like an oversight in WPF, to me. You also cannot style the Width of the columns themselves, as explained by this answer.
It suggests using an attached property, and provides an example which I used for inspiration for my solution. I define this attached property:
public static class DataGridHelper
{
public static DataGridLength GetColumnWidth(DataGrid obj) => (DataGridLength)obj.GetValue(ColumnWidthProperty);
public static void SetColumnWidth(DataGrid obj, DataGridLength value) => obj.SetValue(ColumnWidthProperty, value);
/// <summary>
/// The ColumnWidth attached property sets the Width of all columns.
/// </summary>
public static readonly DependencyProperty ColumnWidthProperty =
DependencyProperty.RegisterAttached("ColumnWidth", typeof(DataGridLength), typeof(DataGridHelper), new PropertyMetadata(ColumnWidthChanged));
private static void ColumnWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var dataGrid = d as DataGrid;
var columns = dataGrid.Columns;
var width = GetColumnWidth(dataGrid);
dataGrid.Columns.CollectionChanged += (s1, e1) => UpdateColumnWidths(columns, width);
UpdateColumnWidths(columns, width);
}
private static void UpdateColumnWidths(ICollection<DataGridColumn> columns, DataGridLength width)
{
foreach (var column in columns) column.Width = width;
}
}
Then use a style to add it to my DataGrids:
<Style TargetType="DataGrid">
<Setter Property="local:DataGridHelper.ColumnWidth" Value="*"/>
</Style>
Upvotes: 0
Reputation: 545
DataGrid.ColumnWidth cannot be applied style as other properties. We have to assign the value explicitly
Upvotes: 2
Reputation:
In the project I'm working on, we make a lot of own controls that are in a ResourceDictionary
. We use the same exact method that you do. So, is your Style
tag in a ResourceDictionary
?
Upvotes: 0