在 xaml 中访问 DisplayName [英] Access DisplayName in xaml

查看:25
本文介绍了在 xaml 中访问 DisplayName的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 XAML 中访问 DisplayName 的值?

How can i access DisplayName's value in XAML?

我有:

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

XAML:

<TextBlock Text="{Binding ??Property.DisplayName??}"/>
<TextBlock Text="{Binding Property}"/>

有没有办法以这种或类似的方式绑定 DisplayName?最好的办法是使用这个 DisplayName 作为资源的键,并从资源中展示一些东西.

Is there any way to bind DisplayName in such or simmilar way? The best idea will be to use this DisplayName as key to Resources and present something from 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;
    }
}

示例用法:

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

public partial class MainWindow : Window
{
   [DisplayName("Awesome Int")]
   public int TestInt { get; set; }
   //...
}

这篇关于在 xaml 中访问 DisplayName的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆