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.
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; }
//...
}
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}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With