我正在尝试使用 C# 和 XAML 将属性元数据显示名称绑定(bind)到 Windows 8 应用程序中的文本 block 。以下是代码:
C#:
[Display(Name="Customer Name")]
public string CustomerName
{
get;
set;
}
XAML:
<TextBlock Text={Binding Name[Obj.CustomerName]} />
如何将 Name 属性绑定(bind)到文本 block 的 Text 属性?
最佳答案
您不能直接这样做,但您可以使用 IValueConverter
,或使用单独的属性。我想说第一个可能是最好的。绑定(bind)将是这样的:
<TextBlock Text="{Binding ConverterParameter='Name',Converter={StaticResource DisplayNameAnnotationConverter}}" />
那么转换器将是这样的:
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();
}
}
不要忘记在资源中的某处包含转换器:
<Application.Resources>
<local:DisplayNameAnnotationConverter x:Key="DisplayNameAnnotationConverter" />
</Application.Resources>
关于c# - Windows 8 将属性属性名称绑定(bind)到 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21325555/