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)
不确定这会扩展得多好,但您可以使用转换器来获取您的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)
| 归档时间: |
|
| 查看次数: |
6153 次 |
| 最近记录: |