在WPF中将静态属性转换为StaticResource

时间:2016-04-11 07:00:16

标签: c# wpf xaml properties converter

我想知道是否可以将类的静态属性转换为静态资源。

我想这样做的原因是因为我制作了一个转换器,它将枚举值转换为人类友好的可读格式(将它们翻译成另一种语言)。

因为我不想为每个enum创建一个转换器,所以我想让事情变得更通用,并使用一个带有两个属性的转换器,enum的类型和字典(IDictionary<string, string>)来映射枚举到想要的输出。

public class EnumTranslatorConverter : IValueConverter
{

    public Type EnumType { get; set; }
    public IDictionary<string, string> EnumMapping { get; set; }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return EnumMapping[value.ToString()];
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return Enum.Parse(EnumType, value as string);
    }
}

然后我得到了一个我定义转换器的资源,以便在我的应用程序中更方便地使用它们。

我想为每种类型和映射定义一个转换器,这只是一个概念证明,因为它当然不起作用:

<mappings:DisplayMappings x:Key="displaymappings" />
<my:EnumTranslatorConverter x:Key="DayOfWeekTranslatorConverter" 
    EnumType="{x:Type sys:DayOfWeek}" 
    EnumMapping="{Binding Source={StaticResource displaymappings}, Path=DayOfWeekMapping}" />

EnumType属性正常运行。但是EnumMapping当然不是因为它需要静态资源,因为它不是依赖属性。

但是如何使用XAML将我的映射注入属性?有没有办法在XAML中用静态属性创建静态资源?

1 个答案:

答案 0 :(得分:1)

静态属性有一个标记扩展名:{x:Static}

<my:EnumTranslatorConverter x:Key="DayOfWeekTranslatorConverter" 
     EnumType="{x:Type sys:DayOfWeek}" 
     EnumMapping="{x:Static mappings:DisplayMappings.DayOfWeekMapping}" />