【发布时间】:2016-08-01 05:05:14
【问题描述】:
我想知道是否可以将类的静态属性转换为静态资源。
我想这样做的原因是因为我制作了一个转换器,它将枚举的值转换为人类友好的可读格式(将它们翻译成另一种语言)。
因为我不想为每个枚举创建一个转换器,所以我想让事情变得更通用,并使用一个具有两个属性的转换器,即枚举的类型和字典 (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 中的静态属性创建静态资源?
【问题讨论】:
标签: c# wpf xaml properties converter