问题描述
我正在尝试列出我的PropertyEntry类(用户控件)的列表,该列表是针对Person类的每个Property生成的。可悲的是,Internet上的大多数指南仅告诉您如何通过XAML文件创建Binding,但是我需要一种无需它即可正常工作的解决方案。所以这是我已经在做的事情:
public partial class PropertyEntry : UserControl
{
public PropertyEntry(string propertyName)
{
Binding propertyBinding = new Binding(); // <--- How do I setup a two-way binding to the PersonToEdit property of the ancestor
InitializeComponent();
this.PropertyLabel.Content = labelName + ": ";
this.PropertyInput.SetBinding(); // <--- How do I apply this binding to my Input
}
}
这里是直接祖先:
public partial class PersonView : Window
{
public Person PersonToEdit { get; set; }
public PersonView(Person person)
{
PersonToEdit = person;
InitializeComponent();
}
public void updateUserControlByUniqueClassFields(object sender,SelectionChangedEventArgs e)
{
PropertyInfo[] varyingPropeties = findVaryingFields();
varyingPropeties.ToList().ForEach((property) =>
{
PropertyList.Children.Add(new PropertyEntry(property.Name)); //<--- Stackpanel
});
}
... more code
}
我想指出,Person类已经实现了IPropertyNotificator,因此以后我可以将OnPropertyChanged事件分配给UpdateSourceTrigger。我只想知道在这种情况下如何通过代码来寻找合适的绑定,因为我不知道如何访问祖先来正确设置新的绑定。
编辑:我正在使用C#WPF 到目前为止,我设法创建了一个Binding,该Binding似乎已绑定到正确的实例,但仍未正确地将属性显示为TextBox.Text。
public partial class PropertyEntry : UserControl
{
public PropertyEntry(Person dataSourceToBind,string propertyName)
{
Binding propertyBinding = new Binding();
propertyBinding.Source = dataSourceToBind;
propertyBinding.Path = new PropertyPath(propertyName);
propertyBinding.Mode = BindingMode.TwoWay;
propertyBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
InitializeComponent();
this.PropertyLabel.Content = propertyName;
this.PropertyInput.SetBinding(TextBlock.TextProperty,propertyBinding);
dataSourceToBind.OnPropertyChanged(propertyName);
}
}
EDIT2 :我找到了解决方案,并希望与大家分享。也许其他人也会遇到同样的困难,并且网络上没有太多有关此问题的代码。所以这行:
this.PropertyInput.SetBinding(TextBlock.TextProperty,propertyBinding);
必须是
BindingOperations.SetBinding(PropertyInput,TextBox.TextProperty,propertyBinding);
相反。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)