【发布时间】: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 的自定义控件,sp 是StackPanel)
绑定代码:
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