c# - Windows 8 将属性属性名称绑定(bind)到 UI

标签 c# windows-8 windows-runtime winrt-xaml windows-8.1

我正在尝试使用 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/

相关文章:

c# - 如何将所有文档从一个 RavenDB 数据库移动到另一个?

winapi - 从 8 和 8.1 开始,Windows SDK 中是否缺少 'dxsdkver.h' 头文件?

c# - 我应该如何解决 WinRT JS 说 null 是 "null"?

javascript - 在javascript中得到错误的总数

c# - 捕捉 System.Exception 总是不好的做法吗?

c# - 获取在 WinRT 中实现给定接口(interface)的所有类

touch - 如何在 Windows 8 中触摸交互后显示指针

javascript - 使用 FileOpenPicker 链接到本地​​计算机上的文件时,音频显示 'Invalid source'

c# - 如何在 C# Windows 8.1 Store App 中翻转和旋转图像

c# - Unity3d 错误 CS2011 : Error opening response file (incorrect temp folder)