Reputation: 622
I am writing a quick and dirty WPF application as a complete WPF novice. I have a simple datagrid:
<DataGrid ItemsSource="{Binding Path=BetterFoods}" Grid.Row="1" Grid.Column="0" AutoGenerateColumns="True" Loaded="DataGrid_Loaded">
<DataGrid.Resources>
<local:ValueColorConverter x:Key="colorconverter"/>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#FF0033"/>
</DataGrid.Resources>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Path=Content.Text, Converter={StaticResource colorconverter}}"/>
</Style>
</DataGrid.CellStyle>
</DataGrid>
The datagrid is coloured by a simple IValueConverter
, which is virtually identical to loads of examples from tutorials and Stack Overflow:
class ValueColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
{
return Brushes.Beige;
}
else if (value is string)
{
string str = ((string)value).Trim();
if (str.Equals(string.Empty))
{
return Brushes.Beige;
}
else if (str.Equals("0"))
{
return Brushes.LightYellow;
}
}
return System.Windows.DependencyProperty.UnsetValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
The IValueConverter
works exactly like it should, but it introduces a strange side effect: selecting a row makes all values in its cells disappear. The values are still there, since changing selection or double-clicking a cell makes them visible again (see .gif below).
This is obviously unfortunate, since one usually highlights a row to have a closer look at its data.
What is causing this behaviour and how do I fix it?
Upvotes: 2
Views: 774
Reputation: 169200
Add a resource (SystemColors.HighlightTextBrushKey) that changes the text brush to something darker so you can actually see the text:
<DataGrid ItemsSource="{Binding Path=BetterFoods}" Grid.Row="1" Grid.Column="0" AutoGenerateColumns="True">
<DataGrid.Resources>
<local:ValueColorConverter x:Key="colorconverter"/>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#FF0033"/>
<!-- ADDED: -->
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black"/>
</DataGrid.Resources>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Path=Content.Text, Converter={StaticResource colorconverter}}"/>
</Style>
</DataGrid.CellStyle>
</DataGrid>
Upvotes: 4