WPF反射,后期绑定

时间:2011-05-27 14:06:30

标签: wpf reflection

我正在尝试从通过XML文件读取的数据设置WPF控件(高度,宽度,字体粗细,边距和许多其他控件)的属性。我不会事先知道要设置哪些属性。我想知道是否有人知道如何通过反思来做到这一点?

目前我已设法使用反射分配所有基本类型和枚举类型,但我对FontWeightMarginBackground等属性有点麻烦以及其他许多需要其他对象来设置属性的例子:要设置按钮的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控件上设置每个可能的属性。

3 个答案:

答案 0 :(得分:1)

在幕后,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")

答案 1 :(得分:1)

实际上非常简单。您将字符串值读取到ViewModel上的属性中,将该视图模型设置为DataContext,并在xaml中绑定属性。 Binding uses TypeConverters automaticall收率

答案 2 :(得分:0)

你可以做这样的事情

typeof(Button).GetProperty("FontWeight").SetValue(button1,GetFontWeight("Bold"), null);

编辑:

您可以使用将字符串转换为属性值的映射函数

FontWeight GetFontWeight(string value)
{

   swithc(value)
   {
     case "Bold" : return FontWeights.Bold; break;
     ...
   }

}
相关问题