问题描述
|
如何在XAML中访问displayName的值?
我有:
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作为资源的键,并显示资源中的内容。
解决方法
我将使用标记扩展名:
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; }
//...
}
, 不确定这样做的扩展程度,但是您可以使用转换器获取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,System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
然后您在XAML中的绑定将如下所示:
Text=\"{Binding Mode=OneWay,Converter={StaticResource ResourceKey=myConverter},ConverterParameter=MyPropertyName}\"