访问颜色资源字典从一个值转换器 [英] Accessing colors in a resource dictionary from a value converter
问题描述
我在ResourceDictionary中定义的几种颜色。 。例如:
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 reuse 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.
搜索结果问候
修改
Application.Current.Resources
不是一个选项。因为我不会有机会获得它以后。
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.
相反,你可以使ResourceDictionary的属性在你的转换,并且设置它,当你实例化转换器。
Instead you could make the ResourceDictionary a property on your converter and set it when you instantiate the 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>
这篇关于访问颜色资源字典从一个值转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!