在xaml中访问DisplayName

Sim*_*mon 15 c# data-binding wpf xaml

如何在XAML中访问DisplayName的值?

我有:

public class ViewModel {
  [DisplayName("My simple property")]
  public string Property {
    get { return "property";}
  }
}
Run Code Online (Sandbox Code Playgroud)

XAML:

<TextBlock Text="{Binding ??Property.DisplayName??}"/>
<TextBlock Text="{Binding Property}"/>
Run Code Online (Sandbox Code Playgroud)

有没有办法以这种或类似的方式绑定DisplayName?最好的想法是使用此DisplayName作为Resources的关键,并从Resources中提供一些内容.

H.B*_*.B. 22

我会使用标记扩展名:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

<TextBlock Text="{m:DisplayName TestInt, Type=local:MainWindow}"/>
Run Code Online (Sandbox Code Playgroud)
public partial class MainWindow : Window
{
   [DisplayName("Awesome Int")]
   public int TestInt { get; set; }
   //...
}
Run Code Online (Sandbox Code Playgroud)

  • 我也会使用MarkupExtension,但它会利用自定义的可本地化DisplayNameAttribute [如此处](http://stackoverflow.com/questions/356464/localization-of-displaynameattribute) (4认同)
  • @GauravGupta:拥有该物业的类型?如果需要,你需要像`{m:DisplayName Property,Type = {x:Type local:MyType \`1}}`这样的数字,其中数字是指泛型参数的数量.[以下是在XAML中使用泛型的示例](http://stackoverflow.com/a/8235459/546730). (2认同)

Gre*_*ora 8

不确定这会扩展得多好,但您可以使用转换器来获取您的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();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你在XAML中的绑定看起来像:

Text="{Binding Mode=OneWay, Converter={StaticResource ResourceKey=myConverter}, ConverterParameter=MyPropertyName}"
Run Code Online (Sandbox Code Playgroud)