问题描述
|
我正在尝试通过XML文件读取的数据设置WPF控件的属性(高度,宽度,字体粗细,边距和许多其他)。我不会知道要预先设置哪些属性。我想知道是否有人知道通过反思来做到这一点的方法?
目前,我已经设法使用反射来分配所有原始类型和枚举类型,但是我对诸如
FontWeight
,Margin
,Background
之类的属性以及其他许多在设置属性时需要其他对象的属性有些麻烦:设置按钮的“ 0”属性,您必须这样做。
button.FontWeight = Fontweights.Bold;
或保证金
button.Margin = new Thickness(10,10,10);
由于可以在WPF中的控件上设置150多个属性,因此我只想避免这种代码。
public void setProperties(String propertyName,string PropertyValue
{
if(propertyName = \"Margin\")
{
Set the margin.....
}
else if (propertyName = \"FontWeight\")
{
set the FontWeight....
}
}
对于WPF控件上可以设置的每个可能的属性,依此类推。
解决方法
在后台,XAML使用ѭ7来将字符串从字符串转换为指定的类型。您可以自己使用它们,因为您提到的每种类型都有使用
TypeConverterAttribute
指定的默认TypeConverter
。您可以像这样使用它(或使方法通用):
object Convert(Type targetType,string value)
{
var converter = TypeDescriptor.GetConverter(targetType);
return converter.ConvertFromString(value);
}
然后,以下每个工作将按预期进行:
Convert(typeof(Thickness),\"0 5 0 0\")
Convert(typeof(FontWeight),\"Bold\")
Convert(typeof(Brush),\"Red\")
, 实际上非常简单。您将字符串值读入ViewModel的属性中,将该视图模型设置为DataContext,然后在xaml中绑定属性。绑定自动使用TypeConverters。
, 你可以做这样的事情
typeof(Button).GetProperty(\"FontWeight\").SetValue(button1,GetFontWeight(\"Bold\"),null);
编辑:
您可以具有将字符串转换为属性值的映射函数
FontWeight GetFontWeight(string value)
{
swithc(value)
{
case \"Bold\" : return FontWeights.Bold; break;
...
}
}