I have a WPF DataGrid showing a DataGridTextColumn with numbers. If the value is negative, I would like to display it in red.
My code compiles, but I get a run time error:
"Cannot find resource named 'PlusBlackMinusRedConverter'. Resource names are case sensitive."
I am sure the converter is in Window.Resources, but my guess is that when the DataGrid constructs the DataCell, it cannot find Window.Resources. Just a guess.
Does anyone know what is the real reason and how to make it work ?
XAML:
<Window x:Class="MyNameSpace.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:MyNameSpace="clr-namespace:MyNameSpace">
<Window.Resources>
<MyNameSpace:TextDoubleToPlusBlackMinusRedConverter x:Key="PlusBlackMinusRedConverter " />
</Window.Resources>
<DockPanel>
<DataGrid Name="stocksDataGrid"
IsReadOnly="True"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=Trend, StringFormat=P}"
Header="Trend">
<DataGridTextColumn.ElementStyle>
<Style>
<Setter Property="TextBlock.Foreground"
Value="{Binding Path=Text, Converter={StaticResource PlusBlackMinusRedConverter }}" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</DockPanel>
</Window>
Code:
using System;
using System.Globalization;
using System.Windows.Data;
namespace MyNameSpace {
public class TextDoubleToPlusBlackMinusRedConverter: IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
if (value is string){
double valueDouble;
if (double.TryParse((string)value, out valueDouble)){
if (valueDouble<0){
return "Red";
} else {
return "Black";
}
}
}
return "Gray";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
throw new NotImplementedException();
}
}
}
You have one unnecessary space after resource name.
Change it to the following code:
<MyNameSpace:TextDoubleToPlusBlackMinusRedConverter x:Key="PlusBlackMinusRedConverter"/>