Reputation: 1190
I'm trying to set a WPF DataGrid row TextBlock's TextWrapping
property to Wrap
when that row is selected, using the same technique shown in this answer.
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Style.Triggers>
<Trigger Property="DataGridCell.IsSelected" Value="True">
<Setter Property="Background" Value="LightBlue" />
<Setter Property="TextBlock.TextWrapping" Value="Wrap" />
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
The background colour changes fine, but the wrapping property does not appear to be set.
I've also tried creating a TextBlock
style, but then had other issues accessing the IsSelected
property. I get the feeling there's a minor change I should be making here.
Edit: It also seems like I might be able to go down the route of styling each DataGridTextColumn
, though I was looking for a more global option especially when columns may be automatically generated.
Upvotes: 2
Views: 533
Reputation: 169150
I've also tried creating a
TextBlock
style, but then had other issues accessing the IsSelected property.
This ElementStyle
should work:
<DataGridTextColumn Binding="{Binding Name}" Width="100">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=DataGridCell}}" Value="True">
<Setter Property="TextWrapping" Value="Wrap" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
If you are auto generating your columns, you could define the ElementStyle
as a resource and handle the AutoGeneratingColumn
event:
private void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
DataGrid dataGrid = (DataGrid)sender;
DataGridTextColumn column = e.Column as DataGridTextColumn;
if (column != null)
{
column.ElementStyle = dataGrid.Resources["ElementStyle"] as Style;
}
}
XAML:
<DataGrid x:Name="dataGrid" AutoGeneratingColumn="dataGrid_AutoGeneratingColumn">
<DataGrid.Resources>
<Style x:Key="ElementStyle" TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=DataGridCell}}" Value="True">
<Setter Property="TextWrapping" Value="Wrap" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
</DataGrid>
Upvotes: 2