【问题标题】:Is it possible to bind to a property using reflection in WPF?是否可以在 WPF 中使用反射绑定到属性?
【发布时间】:2016-12-27 23:32:43
【问题描述】:

我正在编写代码来生成一堆附加到属性的文本框。有什么方法可以将源设置为使用反射找到的属性,存储为PropertyInfo

遍历属性的代码:

foreach(PropertyInfo prop in GetType().GetProperties())
{
    UI.Text ctrl = new UI.Text(prop.Name, prop.GetValue(this).ToString(), prop);
    sp.Children.Add(ctrl);
}

(注意:UI.Text 是包含TextBox 的自定义控件,spStackPanel

绑定代码:

Binding bind = new Binding() { Source = prop };
if (prop.CanWrite)
{
    TextBox.SetBinding(TextBox.TextProperty, bind);
}
else
{
    TextBox.IsEnabled = false;
}

我目前收到错误“双向绑定需要路径或 XPath”,这通常在尝试绑定到只读属性时发生。由于代码受到保护,很明显,简单地绑定到 PropertyInfo 不会绑定到属性本身。

【问题讨论】:

  • 你能展示一下属性实现吗?
  • 将绑定的Path设置为属性的名称,将Source设置为拥有该属性的对象。

标签: c# .net wpf reflection system.reflection


【解决方案1】:

BindingPath 属性设置为prop.Name,将Source 属性设置为this 或您要绑定的任何对象到:

Binding bind = new Binding() { Path = new PropertyPath(prop.Name), Source = this };
if (prop.CanWrite)
{
    TextBox.SetBinding(TextBox.TextProperty, bind);
}
else
{
    TextBox.IsEnabled = false;
}

BindingPath 指定要绑定到的属性,Source 属性指定定义此属性的对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 2018-05-10
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多