Доступ к DisplayName в xaml - PullRequest
       2

Доступ к DisplayName в xaml

15 голосов
/ 27 мая 2011

Как я могу получить доступ к значению 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 в качестве ключа к ресурсам и представить что-то из ресурсов.

Ответы [ 2 ]

22 голосов
/ 27 мая 2011

Я бы использовал расширение разметки :

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; }
   //...
}
8 голосов
/ 27 мая 2011

Не уверен, насколько хорошо это будет масштабироваться, но вы можете использовать конвертер, чтобы добраться до вашего 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}"
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...