Hi,
I have an unbound field in a XamDataGrid that contains two numbers (value, percentage change). Is there a way that I can color one of them to be red while keeping the other black? If it's easy, I can change the value of the field to be html so that I can define the color of each section on the fly. In my testing, I was unable to determine how to use the color nor could I get the html idea to work.
Thanks,
Kyle
Hello Kyle,
It is possible to change the default ItemTemplate of the editor that is used in each cell so that the TextBlock contains multiple Run elements. Then you should be able to specify different foreground for each one. Another option is to replace the TextBlock with a ContentControl and bind the Content with a converter. In the converter you will return new Textblock control with custom Inline collection:
<Border x:Name="MainBorder"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}">
<ContentControl Content="{TemplateBinding DisplayText,
Converter={StaticResource conv}}"/>
</Border>
Converter's code:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string s = value.ToString();
Run r1 = new Run () { Text = s, Foreground = Brushes .Red };
Run r2 = new Run () { Text = "%" , Foreground = Brushes .Blue };
TextBlock tb = new TextBlock ();
tb.Inlines.Add(r1);
tb.Inlines.Add(r2);
return tb;
}
Let me know if this works for you and if you have any questions.
Hi Vlad,
My unbound field is defined on-the-fly in the C# code as such, where my TestConverter class looks like your converter code (see below). However, since the grid contains both unbound and bound fields, it doesn't like the results of my convert (the TextBlock) and displays in this column, "System.Windows.Controls.TextBlock", instead of the values. When I define my UnboundField in the c# code, do I need to define my template there too?
UnboundField f = new UnboundField();
f.Name = col.HeaderName;
f.Label = col.HeaderName;
f.DataType = typeof(string);
f.Converter = new TestConverter();
You can create the style as a resource in xaml and then set it on the UnboundField using the f.Settings.EditorStyle property.
Let me know if you need any assistance with this.
I've been able to set the editorstyle of the color. However, that style only contains the color of the entire cell; not piecewise coloring which is what I need. Are you talking about having the style define the template? Since the converter returns a TextBlock, the grid needs to know how to convert that into its value. What style would I use to tell the grid there?
Please, find the attached sample and let me know if this works for you and if you have any questions.