Yesterday, I came across a situation where I needed a single item from my view model (an enum value) to affect two properties on a WPF element (the Foreground and Background colors of a DataGridCell). I’m familiar with value converters, but they only convert to a single value. I did some research on MultiValueConverters, but, as seasoned WPF developer Anne Marsan pointed out, they take multiple inputs but still only produce a single output. How to proceed?
NOTE: I’ve provided sample code in a BitBucket project here. Each “attempt” that I detail below is tagged in the repository so you can easily see the implementations of each approach by switching your working directory to a certain tag.
First Attempt (Tag: Attempt1)
My first attempt was brute force and worked, but was messy – I simply created two value converters: both would take my enum, but one would return the background color and one would return the foreground color.
[ValueConversion(typeof(CompareResult), typeof(String))]
class ForeColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var result = (CompareResult)value;
var ci = ColorInformation.FromResult(result);
return ci.ForeColor;
}
Read more: Patrick Steele's .NET Blog
QR: