2012-08-12 3 views
0

WPF에서 바인딩을 알아 내고 객체 바인딩 문제가 발생했습니다.개체를 설정할 때 바인딩을 유지하는 방법은 무엇입니까?

나는 사용자

ICollection<User> users = User.GetAll(); 
cmbContacts.ItemsSource = users;  

나는 또한 선택한 사용자를 보유하고 내 UI에서 개체를 목록으로 설정 한 itemsource와 콤보 상자가 있습니다.

public partial class MainWindow : Window 
{ 

    private User selectedUser = new User(); 

    public MainWindow() 
    { 
     InitializeComponent(); 
     ReloadContents(); 

     Binding b = new Binding(); 
     b.Source = selectedUser; 
     b.Path = new PropertyPath("uFirstName"); 
     this.txtFirstName.SetBinding(TextBox.TextProperty, b); 
    } 

그리고 내 콤보 상자의 SelectChanged 방법에 ...

selectedUser = (User)e.AddedItems[0]; 

그러나, 텍스트 상자가 업데이트되지 않는다! 나는 콤보 상자에 바인딩 코드를 이동하여 내 바인딩 작품이 텍스트 상자 미세 업데이트 이제 방법을

selectedUser = (User)e.AddedItems[0];  
Binding b = new Binding(); 
b.Source = selectedUser; 
b.Path = new PropertyPath("uFirstName"); 
this.txtFirstName.SetBinding(TextBox.TextProperty, b); 

을 SelectChanged 확인할 수 있습니다. 이것은 잘못된 일을하는 것처럼 보입니다. 누구든지 올바른 방향으로 나를 가리킬 수 있습니까?

답변

0

코드에 하나의 버그가 있습니다. 선택한 사용자 필드를 설정하면이 데이터가 변경되었음을 알리지 않습니다. 귀하의 샘플을해야는 다음과 같습니다

public partial class MainWindow : Window, INotifyPropertyChanged 
{ 
    private User selectedUser; 

    public User SelectedUser 
    { 
     get 
     { 
      return selectedUser; 
     } 
     set 
     { 
      selectedUser = value; 
      NotifyPropertyChanged("SelectedUser"); 
     } 
    } 

    public MainWindow() 
    { 
     InitializeComponent(); 
     ReloadContents(); 

     // Now the source is the current object (Window), which implements 
     // INotifyPropertyChanged and can tell to WPF infrastracture when 
     // SelectedUser property will change value 
     Binding b = new Binding(); 
     b.Source = this; 
     b.Path = new PropertyPath("SelectedUser.uFirstName"); 
     this.txtFirstName.SetBinding(TextBox.TextProperty, b); 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    private void NotifyPropertyChanged(string info) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(info)); 
     } 
    } 
} 

그리고 지금 당신이 필드를 사용하지 마십시오 속성에 새 값을 설정해야합니다 잊지 마세요, 그래서 SelectChanged는해야 다음과 같습니다

SelectedUser = (User)e.AddedItems[0]; 
+0

또한 MVVM 패턴을 살펴보십시오. View 및 ViewModel을 별도로 보유하는 것이 더 좋습니다. – outcoldman

+0

잘 했어! 나는 내 사용자 클래스에 INotifyPropertyChanged를 가졌지 만 어떤 이유로 트리거가 발생하지 않았습니다. –

관련 문제