2

I am trying to bind a property metadata Display Name to a textblock in a Windows 8 app using C# and XAML. Following is the code:

C#:

[Display(Name="Customer Name")]
public string CustomerName
{
get;
set;
}

XAML:

<TextBlock Text={Binding Name[Obj.CustomerName]} />

How can i bind Name attribute to the Text property of textblock?

Charles Stevens
  • 1,568
  • 15
  • 30
Balraj Singh
  • 3,381
  • 6
  • 47
  • 82

1 Answers1

0

You can't do it directly, but you could either use an IValueConverter, or use a separate property. I'd say the first is probably best. Binding would be like this:

<TextBlock Text="{Binding ConverterParameter='Name',Converter={StaticResource DisplayNameAnnotationConverter}}" />

Then the converter would be something like this:

public class DisplayNameAnnotationConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null)
        {
            // for Windows 8, need Type.GetTypeInfo() and GetDeclaredProperty
            // http://msdn.microsoft.com/en-us/library/windows/apps/br230302%28v=VS.85%29.aspx#reflection
            // http://msdn.microsoft.com/en-us/library/windows/apps/hh535795(v=vs.85).aspx
            var prop = value.GetType().GetTypeInfo().GetDeclaredProperty((string)parameter);
            if (prop != null)
            {
                var att = prop.GetCustomAttributes(false).OfType<DisplayAttribute>().FirstOrDefault() as DisplayAttribute;
                if (att != null)
                    return att.DisplayName;
            }
        }
        return DependencyProperty.UnsetValue;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Don't forget to include the converter somewhere in your resources:

<Application.Resources>
    <local:DisplayNameAnnotationConverter x:Key="DisplayNameAnnotationConverter" />
</Application.Resources>
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • value.GetType().GetProperty() is showing error there is no method like GetProperty in Windows 8 – Balraj Singh Jan 24 '14 at 06:32
  • @BalrajSingh my mistake ... see my edit above. I guess you need "GetTypeInfo" for Windows 8. http://stackoverflow.com/a/7858705/1001985 – McGarnagle Jan 24 '14 at 08:12