【问题标题】:Windows 8 Bind property attribute Name to the UIWindows 8 将属性属性名称绑定到 UI
【发布时间】:2014-01-24 16:17:19
【问题描述】:

我正在尝试使用 C# 和 XAML 将属性元数据显示名称绑定到 Windows 8 应用程序中的文本块。以下是代码:

C#:

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

XAML:

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

如何将 Name 属性绑定到 textblock 的 Text 属性?

【问题讨论】:

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


    【解决方案1】:

    您不能直接执行此操作,但您可以使用IValueConverter,或使用单独的属性。我会说第一个可能是最好的。绑定是这样的:

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

    【讨论】:

    • value.GetType().GetProperty() 显示错误 Windows 8 中没有像 GetProperty 这样的方法
    • @BalrajSingh 我的错误......请参阅上面的编辑。我猜你需要 Windows 8 的“GetTypeInfo”。stackoverflow.com/a/7858705/1001985
    猜你喜欢
    • 2011-09-01
    • 1970-01-01
    • 2020-03-25
    • 2013-01-30
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    相关资源
    最近更新 更多