Wpf 获取绑定属性';s PropertyInfo
我想要实现的是为属性指定特定的值,这些属性只应在设计器中显示,而不应在运行时显示Wpf 获取绑定属性';s PropertyInfo,wpf,binding,converter,propertyinfo,Wpf,Binding,Converter,Propertyinfo,我想要实现的是为属性指定特定的值,这些属性只应在设计器中显示,而不应在运行时显示 因此,在我的ViewModels中,我想用自定义属性装饰属性 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class DesignTimeValueAttribute : Attribute { public object Value { get; } public DesignTimeVal
因此,在我的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>
但是我不知道是否有办法获取绑定属性PropertyInfo
如何访问
IValueConverter
中的实际属性,而不仅仅是值及其类型?
我可以传递什么作为转换器参数,例如,我可以使用
<TextBox Text="{Binding Test, Converter={StaticResource DesignTimeValueConverter}, ConverterParameter=???}" />
如果是,我应该传递什么?要从DesignTimeValueAttribute获取属性值,值转换器必须使用反射,如下所示:
((DisplayAttribute(typeof(className).GetProperty(propertyName).GetCustomAttribute(typeof(DisplayAttribute)))).DesignTimeValue;
要使用反射,需要两件事:
<UserControl.Resources>
<local:DesignTimeValueConverter x:Key="myDesignTimeValueConverter" ClassName="MyNamespace.MyClass" />
</UserControl.Resources>
然后对属性使用转换器,并将属性名称作为ConverterParameter传递:
<TextBlock Text="{Binding Test, Converter={StaticResource myDesignTimeValueConverter}, ConverterParameter=Test}" />
<TextBlock Text="{Binding Test, Converter={StaticResource myDesignTimeValueConverter}, ConverterParameter=Test}" />