Accessing colors in a resource dictionary from a value converter
I defined several colors in a ResourceDictionary. e.g.:
<ResourceDictionary ...>
<Color x:Key=Gray1>#FFF7F1F3</Color>
<Color x:Key=Gray2>#FFDDD8DA</Color>
</ResourceDictionary>
So I can r开发者_JS百科euse them everywhere in application.
Now I wrote a value converter to convert the items inner state to the related color.
How can I access the defined colors in the code of the value converter?
My first thought was to pass the dictionary as converter parameter. But I don't know how to achieve that.
RegardsEDIT
Application.Current.Resources
is not an option. Because I won't have access to it later.
The annoying thing about using a converter parameter is that you have to add that text every single time you want to use the binding.
Instead you could make the ResourceDictionary a property on your converter and set it when you instantiate the converter.
code for converter:
public class SomeConverter : IValueConverter
{
private ResourceDictionary _resourceDictionary;
public ResourceDictionary ResourceDictionary
{
get { return _resourceDictionary; }
set
{
_resourceDictionary = value;
}
}
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
//do your own thing using the _dict
//var person = value as Person
//if (person.Status == "Awesome")
// return _resourceDictionary["AwesomeBrush"]
//else
// return _resourceDictionary["NotAwesomeBrush"];
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
instantiate and use converter:
<Window.Resources>
<local:SomeConverter x:Key="MyConverter" >
<local:SomeConverter.ResourceDictionary>
<ResourceDictionary Source="SomeRandomResourceDictionary.xaml" />
</local:SomeConverter.ResourceDictionary>
</local:SomeConverter>
</Window.Resources>
...
<StackPanel Background="{Binding CurrentPerson, Converter={StaticResource MyConverter}}" >
</StackPanel>
精彩评论