Доступ к DisplayName в xaml
Как я могу получить доступ к значению DisplayName в 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 как ключ к ресурсам и представить что-то из ресурсов.
Ответы
Ответ 1
Я бы использовал расширение :
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; }
//...
}
Ответ 2
Не уверен, насколько это масштабируется, но вы можете использовать конвертер, чтобы добраться до вашего 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();
}
}
а затем ваша привязка в XAML будет выглядеть так:
Text="{Binding Mode=OneWay, Converter={StaticResource ResourceKey=myConverter}, ConverterParameter=MyPropertyName}"