从值转换器访问资源字典中的颜色 [英] Accessing colors in a resource dictionary from a value converter

查看:11
本文介绍了从值转换器访问资源字典中的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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();
    }

}

实例化并使用转换器:

<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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆