[英]WPF TwoWay binding in multiple UserControl
我有多个UserControl
包含一个共享的ViewModel
。
这是一个DataGrid
,用户可以在其中单击行以查看行的详细信息(实际结构更为复杂)。
问题是,当我处理网格中的SelectionChanged
时,我更新了共享的ViewModel
以更新ContactDetail,但它没有更新TextBoxes
的值(该对象在ContactDetail中已更新,但未显示值)。
ListContact.xaml.cs
public void contactsTable_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
contacts.current_identity = //Get the associated `IdentityViewModel`
}
ContactDetail.xaml.cs
public partial class ContactDetail : UserControl
{
public ContactsViewModel contacts;
public DetailContact(ContactsViewModel contacts)
{
InitializeComponent();
this.contacts = contacts;
this.DataContext = contacts;
}
}
ContactDetail.xaml
<UserControl x:Class="ContactDetail">
<TextBox Name='address' Text="{Binding Path=contacts.current_identity.address, Mode=TwoWay}"/>
<TextBox Name='phone' Text="{Binding Path=contacts.current_identity.phone, Mode=TwoWay}"/>
<TextBox Name='email' Text="{Binding Path=contacts.current_identity.email, Mode=TwoWay}"/>
</UserControl>
ContactsViewModel.cs (IdentityViewModel使用相同的结构)
public class ContactsViewModel : INotifyPropertyChanged
{
private List<Contact> _contacts;
public List<Contact> contacts;
{
get { return _contacts; }
set { _contacts = value; OnPropertyChanged("contacts"); }
}
private IdentityViewModel _current_identity;
public IdentityViewModel current_identity
{
get { return _current_identity; }
set { _current_identity = value; OnPropertyChanged("current_identity"); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
问题是,为什么这不起作用,以及如何通知ContactDetail
以便显示新值?
联系人的数据已更改,但是Binding Path=contacts.current_identity.address
中仍引用原始参考位置Binding Path=contacts.current_identity.address
。 IE address
仍然有效,并且没有更改。 更改的是contacts.current
但您对此没有约束。
请记住,绑定只是对位置参考的反映。 如果原始address
发生变化,您将看到一个变化,因为这就是寻找变化的原因。 但是父实例却发生了变化。
您需要重构绑定以允许在current_identity
更改时进行适当的更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.