我正在尝试从通过XML文件读取的数据中设置WPF控件(高度、宽度、字体宽度、边距和许多其他)的属性。我不知道要预先设置哪些属性。我想知道有没有人知道如何通过反射来做到这一点?
目前,我已经设法使用反射分配了所有的原语类型和枚举类型,但我在使用FontWeight、Margin、Background和许多其他在设置属性时需要其他对象的属性时遇到了一些麻烦。例如:要设置按钮的FontWeight属性,必须这样做。
button.FontWeight = Fontweights.Bold;或保证金
button.Margin = new Thickness(10, 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控件上设置的每个可能的属性,依此类推。
发布于 2011-05-28 05:15:26
在幕后,XAML使用TypeConverter将字符串转换为指定的类型。您可以自己使用它们,因为您提到的每个类型都有一个使用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")发布于 2011-06-16 00:52:33
这实际上非常简单。将字符串值读取到ViewModel上的属性中,将视图模型设置为DataContext,然后在xaml中绑定属性。Binding uses TypeConverters automatically.
发布于 2011-05-27 22:11:52
你可以这样做
typeof(Button).GetProperty("FontWeight").SetValue(button1,GetFontWeight("Bold"), null);编辑:
您可以使用一个映射函数将字符串转换为属性值
FontWeight GetFontWeight(string value)
{
swithc(value)
{
case "Bold" : return FontWeights.Bold; break;
...
}
}https://stackoverflow.com/questions/6153387
复制相似问题