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

查看:231
本文介绍了在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天全站免登陆