Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access DisplayName in xaml

How can i access DisplayName's value in XAML?

I've got:

public class ViewModel {
  [DisplayName("My simple property")]
  public string Property {
    get { return "property";}
  }
}

XAML:

<TextBlock Text="{Binding ??Property.DisplayName??}"/>
<TextBlock Text="{Binding Property}"/>

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.

like image 469
Simon Avatar asked May 27 '11 14:05

Simon


2 Answers

I would use a markup extension:

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;
    }
}

Example usage:

<TextBlock Text="{m:DisplayName TestInt, Type=local:MainWindow}"/>
public partial class MainWindow : Window
{
   [DisplayName("Awesome Int")]
   public int TestInt { get; set; }
   //...
}
like image 145
H.B. Avatar answered Oct 26 '22 23:10

H.B.


Not sure how well this would scale, but you could use a converter to get to your DisplayName. The converter would look something like:

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();
    }
}

and then your binding in XAML would look like:

Text="{Binding Mode=OneWay, Converter={StaticResource ResourceKey=myConverter}, ConverterParameter=MyPropertyName}"
like image 20
Greg Andora Avatar answered Oct 26 '22 23:10

Greg Andora