[英]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.