代码之家  ›  专栏  ›  技术社区  ›  Thomas Flinkow

获取绑定属性的PropertyInfo

  •  0
  • Thomas Flinkow  · 技术社区  · 7 年前

    我要实现的是为属性指定特定的值,这些值只应在设计器中显示,而不应在运行时显示。


    所以在我的ViewModels中,我想用一个自定义属性来装饰属性

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class DesignTimeValueAttribute : Attribute
    {
        public object Value { get; }
    
        public DesignTimeValueAttribute(object value)
        {
            this.Value = value;
        }
    }
    

    比如这个:

    private string test;
    
    [DesignTimeValue("Hello World")]
    public string Test
    {
        get { return this.test; }
        set
        {
            if(this.test != value)
            {
                this.test = value;
                this.RaisePropertyChanged();
            }
        }
    }
    

    在XAML部分,我想绑定到如下属性:

    <Window.Resources>
        <DesignTimeValueConverter x:Key="DesignTimeValueConverter" />
    </Window.Resources>
    
    <Grid>
        <TextBox Text="{Binding Test, Converter={StaticResource DesignTimeValueConverter}}" />
    </Grid>
    

    到现在为止,一直都还不错。这个 DesignTimeValueConverter 应该 如下所示(伪代码):

    public class DesignTimeValueConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (DesignerProperties.GetIsInDesignMode(this))
            {
                PropertyInfo propertyInfo = ...; // What can I put here?
                DesignTimeValueAttribute attribute = propertyInfo.GetCustomAttribute<DesignTimeValueAttribute>();
    
                if(attribute != null)
                {
                    return attribute.Value;
                }
            }
    
            return value;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
    }
    

    但我不知道是否有方法获取绑定的属性 PropertyInfo .


    如何访问 IValueConverter ,不仅是值及其类型?

    我可以传递什么作为转换器参数,例如,我可以使用

    <TextBox Text="{Binding Test, Converter={StaticResource DesignTimeValueConverter}, ConverterParameter=???}" />
    

    如果是,我应该通过什么?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Shivani Katukota    7 年前

    要从DesignTimeValueAttribute获取属性值,值转换器必须使用如下反射:

    ((DisplayAttribute(typeof(className).GetProperty(propertyName).GetCustomAttribute(typeof(DisplayAttribute)))).DesignTimeValue;
    

    要使用反射,需要两件事:

    1. 这些属性所在的类的名称
    2. 物业名称

    可以将类名的DependencyProperty添加到值转换器,也可以创建多值转换器并将类的名称作为绑定之一传递。

    <UserControl.Resources>
        <local:DesignTimeValueConverter x:Key="myDesignTimeValueConverter" ClassName="MyNamespace.MyClass" />
    </UserControl.Resources>
    

    然后对属性使用转换器,并将属性名称作为转换器参数传递:

    <TextBlock Text="{Binding Test, Converter={StaticResource myDesignTimeValueConverter}, ConverterParameter=Test}" />