在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; }
//...
}