2017-11-30 11 views
0

UserControlViewModel 공유가 여러 개 있습니다.WPF TwoWay 바인딩에 여러 UserControl

Overview here

그것이 행의 사용자 클릭은 로우의 내용을 볼 수있어 DataGrid (실제 구조가 더 복잡하다). 나는 그리드에서 SelectionChanged을 처리 할 때

문제

는, 나는 ContactDetail를 업데이트 할 수있는 공유 ViewModel를 업데이트하지만 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; 
    } 
} 

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

ContactDetail.xaml 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을 통보 않습니다입니까?

+1

참조 ("포인터") 자체를 변경하지 않는 한 참조 형식의 인스턴스를 'ref'로 전달할 필요가 없습니다. 'class' 인스턴스는 항상 참조에 의해 전달 될 것이고'struct'가 복사 될 것입니다. – dymanoid

+0

뷰 모델이 필요할 때 'PropertyChanged' 이벤트를 발생 시키시겠습니까? 보기 - 모델을 게시하십시오. – dymanoid

+0

@dymanoid 편집되었습니다. 그렇습니다. – BadMiscuit

답변

2

연락처에 대한 데이터는 변경되지만 원래 참조 위치 Binding Path=contacts.current_identity.address은 여전히 ​​바인딩에서 참조됩니다. I.E. address은 여전히 ​​유효하며 변경되지 않았습니다. 변경된 내용은 contacts.current이지만 바인딩하지 않았습니다.

바인딩은 단순히 위치 참조으로의 반사라는 것을 기억하십시오. 원래 address이 변경되면 변경 사항이 표시되므로 변경 사항이 표시됩니다. 하지만 대신 부모 인스턴스가 바뀌 었습니다.

current_identity이 변경되면 올바른 업데이트가 가능하도록 바인딩을 리팩토링해야합니다.

+0

답변 해 주셔서 감사합니다. "current_identity가 바뀔 때 적절한 업데이트가 가능하도록 바인딩을 리팩터링해야합니다." 'current_identity'를 변경할 때마다'DataContext'를 업데이트해야합니까? – BadMiscuit

+0

사실, OnPropertyChanged 이벤트를 잡아 내고 각각의 'UserControl'에서 데이터를 리 바인드합니다. 어떻게 든'DataSource'를 재정의하고 DataContext를 다시 정의 할 때'TextBox'를 사용하지 않고'DataGrid'와 함께 작동합니다. – BadMiscuit