簡體   English   中英

多個UserControl中的WPF TwoWay綁定

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM