繁体   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