Reputation: 1066
I am trying to set the background color of a DataGridTextColumn
to another color if it is read-only. I am doing so with the following code:
<DataGridTextColumn Header="Test" IsReadOnly="True">
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsReadOnly, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGridTextColumn}}}" Value="True">
<Setter Property="Background" Value="LightGreen"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
I am having no luck, however removing the triggers results in the background always being light green. Is something wrong with the data trigger binding? I am relatively new to WPF but this is what I could find online. Ideally this would be in App.XAML so it would work across all columns such as this, so would there then be a way to translate this to a style? Thanks.
Edit---------
If I bind by ElementName it works:
<DataTrigger Binding="{Binding IsReadOnly, ElementName=stupid}" Value="True">
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
However I would like this to be more generic if possible. Thanks again.
Upvotes: 3
Views: 8095
Reputation: 488
Edit: Didn't check for a background property on DataGridTextColumn at first.
This answered your original question -
<DataGridTextColumn Header="Test" IsReadOnly="True" Binding="{Binding name}" x:Name="MyColumn">
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsReadOnly, ElementName=MyColumn}" Value="True">
<Setter Property="Background" Value="Orange" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
To answer your second question, the DataTrigger binding you are looking for is:
<DataTrigger Binding="{Binding IsReadOnly, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridCell}}}" Value="True">
In Summary, look for the parent DataGridCell instead of DataGridTextColumn. The reason for this is the TextBlock you are trying to style is not actually a child of DataGridTextColumn, but a child of the DataGridTextColumn's peer.
Upvotes: 1