My goal is to change the Background (Brush) of a Control based on a certain Text property of the datasource.
I made that happen in a simpler (working) example when my converter had only 2 Properties for the brush:
<local:ListErrorWarndescriptionToColorConverter x:Key="ErrorListToColor"
NormalBrush="Transparent" ErrorBrush="Red" WarnBrush="Yellow"/>
Next step was to write that converter to handle more than 2 Strings
My converter code:
public class StringToBrushDictionary : Dictionary<string, Brush> { }
[ValueConversion(typeof(string), typeof(Brush))]
public sealed class TextToBrushConverter : IValueConverter
{
public StringToBrushDictionary LookUpTable { get; set; }
public Brush Default { get; set; }
public TextToBrushConverter()
{
// set defaults
LookUpTable = new StringToBrushDictionary();
Default = Brushes.Transparent;
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var collection = value as string;
if (collection == null)
return Default;
if (LookUpTable.ContainsKey(collection))
return LookUpTable[collection];
return Default;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
My Problem now is: How do I fill that dictionary in xaml I found this 8 year old question but it isn't exactly what I need because it uses string and int, two "native" datatypes and also uses VS 2010, which has no support for dictionaries (according to the answers there). An answer there stated that a later XAML version could do this, but VS 2010 did not implement it, yet.
Here is my take on the converter Markup and what I tried already:
<Application x:Class="BetterListbox.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BetterListbox"
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:collections="clr-namespace:System.Collections;assembly=mscorlib"
xmlns:Specialized="clr-namespace:System.Collections.Specialized;assembly=System"
StartupUri="MainWindow.xaml">
<Application.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVis" />
<local:ListErrorWarndescriptionToColorConverter x:Key="ErrorListToColor"
NormalBrush="Transparent" ErrorBrush="Red" WarnBrush="Yellow"/>
<local:TextToBrushConverter x:Key="WarnErrorToBrush" Default="Red">
<local:TextToBrushConverter.LookUpTable>
<local:StringToBrushDictionary>
<Brush x:Key="Error" >
...?
</Brush>
<collections:DictionaryEntry x:Key="d" Value="Brushes.Red" />
</local:StringToBrushDictionary>
</local:TextToBrushConverter.LookUpTable>
</local:TextToBrushConverter>
</Application.Resources>
</Application>
Is it even possible to fill LookUpTable
in xaml and, if yes, how?