C# 在xaml中访问DisplayName

C# 在xaml中访问DisplayName,c#,wpf,xaml,data-binding,C#,Wpf,Xaml,Data Binding,如何在XAML中访问DisplayName的值 我有: public class ViewModel { [DisplayName("My simple property")] public string Property { get { return "property";} } } XAML: 有没有办法以这种或类似的方式绑定DisplayName?最好的办法是使用此DisplayName作为资源的键,并从资源中呈现一些内容。不确定这会扩展到多大程度,但您可以使用转

如何在XAML中访问DisplayName的值

我有:

public class ViewModel {
  [DisplayName("My simple property")]
  public string Property {
    get { return "property";}
  }
}
XAML:



有没有办法以这种或类似的方式绑定DisplayName?最好的办法是使用此DisplayName作为资源的键,并从资源中呈现一些内容。

不确定这会扩展到多大程度,但您可以使用转换器来获取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}"
我会使用:

用法示例:

<TextBlock Text="{m:DisplayName TestInt, Type=local:MainWindow}"/>

我也会使用MarkupExtension,但它利用了自定义的可本地化DisplayNameAttribute,如@Code裸体:好主意,虽然我知道本地化问题,但我自己没有想到任何特殊的方法。如果底层类型是泛型对象,我们如何使其工作?@GauravGupta:拥有该属性的类型?如果是这样,您需要类似于
{m:DisplayName属性,Type={x:Type local:MyType`1}}
的内容,其中数字指的是泛型参数的数量。
<TextBlock Text="{m:DisplayName TestInt, Type=local:MainWindow}"/>