在xaml中访问DisplayName
如何在XAML中访问DisplayName的值?
我有:
public class ViewModel { [DisplayName("My simple property")] public string Property { get { return "property";} } }
XAML:
有没有办法以这种或类似的方式绑定DisplayName? 最好的想法是使用此DisplayName作为Resources的关键,并从Resources中提供一些内容。
我会使用标记扩展名 :
public class DisplayNameExtension : MarkupExtension { public Type Type { get; set; } public string PropertyName { get; set; } public DisplayNameExtension() { } public DisplayNameExtension(string propertyName) { PropertyName = propertyName; } public override object ProvideValue(IServiceProvider serviceProvider) { // (This code has zero tolerance) var prop = Type.GetProperty(PropertyName); var attributes = prop.GetCustomAttributes(typeof(DisplayNameAttribute), false); return (attributes[0] as DisplayNameAttribute).DisplayName; } }
用法示例:
public partial class MainWindow : Window { [DisplayName("Awesome Int")] public int TestInt { get; set; } //... }
不确定这会扩展得多好,但您可以使用转换器来获取您的DisplayName。 转换器看起来像:
public class DisplayNameConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { PropertyInfo propInfo = value.GetType().GetProperty(parameter.ToString()); var attrib = propInfo.GetCustomAttributes(typeof(System.ComponentModel.DisplayNameAttribute), false); if (attrib.Count() > 0) { return ((System.ComponentModel.DisplayNameAttribute)attrib.First()).DisplayName; } return String.Empty; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } }
然后你在XAML中的绑定看起来像:
Text="{Binding Mode=OneWay, Converter={StaticResource ResourceKey=myConverter}, ConverterParameter=MyPropertyName}"