我正在计算WPF中的绑定,并遇到了对象绑定的问题。
我有一个组合框,其中itemsource设置为用户列表
ICollection<User> users = User.GetAll();
cmbContacts.ItemsSource = users;
我的UI中还有一个对象,用于保存所选用户。
public partial class MainWindow : Window
{
private User selectedUser = new User();
public MainWindow()
{
InitializeComponent();
ReloadContents();
Binding b = new Binding();
b.Source = selectedUser;
b.Path = new PropertyPath("uFirstName");
this.txtFirstName.SetBinding(TextBox.TextProperty, b);
}
在我的组合框的SelectChanged方法......
selectedUser = (User)e.AddedItems[0];
但是,文本框没有更新!我可以通过将绑定代码移动到组合框SelectChanged方法
来验证我的绑定是否有效selectedUser = (User)e.AddedItems[0];
Binding b = new Binding();
b.Source = selectedUser;
b.Path = new PropertyPath("uFirstName");
this.txtFirstName.SetBinding(TextBox.TextProperty, b);
现在文本框更新正常。这似乎是不正确的做事方式。有人能指出我正确的方向吗?
答案 0 :(得分:0)
在您的代码中,我看到一个错误 - 当您设置字段selectedUser时,您不会通知此数据已被更改。您的样本应如下所示:
public partial class MainWindow : Window, INotifyPropertyChanged
{
private User selectedUser;
public User SelectedUser
{
get
{
return selectedUser;
}
set
{
selectedUser = value;
NotifyPropertyChanged("SelectedUser");
}
}
public MainWindow()
{
InitializeComponent();
ReloadContents();
// Now the source is the current object (Window), which implements
// INotifyPropertyChanged and can tell to WPF infrastracture when
// SelectedUser property will change value
Binding b = new Binding();
b.Source = this;
b.Path = new PropertyPath("SelectedUser.uFirstName");
this.txtFirstName.SetBinding(TextBox.TextProperty, b);
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
不要忘记现在你需要为属性设置新值,不要使用字段,所以SelectChanged应该是这样的:
SelectedUser = (User)e.AddedItems[0];