【问题标题】:WPF Reflection, Late BindingWPF 反射,后期绑定
【发布时间】:2011-05-27 14:06:29
【问题描述】:

我正在尝试从通过 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 控件上设置的每个可能的属性,依此类推。

【问题讨论】:

  • 这与您的其他question 有何不同?

标签: wpf reflection


【解决方案1】:

在幕后,XAML 使用TypeConverters 将字符串转换为指定的类型。您可以自己使用它们,因为您提到的每种类型都有一个使用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")

【讨论】:

    【解决方案2】:

    其实很简单。您将字符串值读入 ViewModel 上的属性,将该视图模型设置为 DataContext,然后在 xaml 中绑定您的属性。 Binding uses TypeConverters automatically.

    【讨论】:

      【解决方案3】:

      你可以这样做

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

      编辑:

      你可以有一个将字符串转换为属性值的映射函数

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

      【讨论】:

      • 感谢您的回答,但是对于您的代码,我仍然必须知道我要设置它是 FontWeight 属性,以便将 FontWeights.Bold 对象传递给 setValue 方法。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-15
      相关资源
      最近更新 更多