2016-12-27 85 views
0

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

代码通过属性会:

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是包含文本框自定义控制,和SP是一个StackPanel)

绑定代码:

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

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

+0

你可以显示财产执行? –

+0

将Binding的'Path'设置为属性的名称,将Source设置为拥有该属性的对象。 – Clemens

回答

1

设置绑定到prop.Name的路径属性和Source属性这个或要绑定到任何对象:

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

绑定的路径指定属性绑定到并且Source属性指定了该属性被定义的对象。

相关问题