2011-11-01 39 views
0

我在我的視圖中更新文本框文本時遇到問題。我已經看到一些其他線程,但無法找到一個接近我的設置。綁定的文本框文本不會更新

我有一類

interface IPerson : INotifyPropertyChanged 
    { 
     string FirstName { get; set;}  
    } 

    public class Person 
    { 
     public event PropertyChangedEventHandler PropertyChanged = delegate { }; 
     private string _firstName; 
     public string FirstName 
     { 
      get {return _firstName;} 
      set 
      { 
      _firstName = value; 
      PropertyChanged(this , new PropertChangedEventArgs("FirstName")); 
      } 
     } 
    } 

模型這是我的視圖模型看起來像

interface IViewModel : INotifyPropertyChanged 
    { 
     string FirstName { get; set;} 
     IPerson Person { get; set; } 
    } 
    public class viewModel : IViewModel 
    { 
     public event PropertyChangedEventHandler PropertyChanged = delegate { }; 
     private IPerson _person; 
     public Person Person 
     { 
     get {return _person;} 
     set 
      { 
       _person = value; 
       PropertyChanged(this , new PropertyChangedEventArgs("Person")); 
      } 
     }   
     public string FirstName 
     { 
      get {return Person.FirstName;} 
      Set 
      { 
       Person.FirstName = value; 
       PropertyChanged(this , new PropertChangedEventArgs("FirstName")); 
      } 

     } 
    } 

XAML綁定設置

// If i use this binding my model will get updated but my textbox text will never show what the value is in the model 
Text="{Binding Path=FirstName ,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay,diag:PresentationTraceSources.TraceLevel=High}" 

// This binding works fine both ways 
Text="{Binding Path=Person.FirstName ,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay,diag:PresentationTraceSources.TraceLevel=High}" 

所以,如果我綁定到人。名字一切都很好。如果我綁定到名字,那麼它會更新我的模型,但不會獲取文本框文本的數據。當我在列表中選擇一個項目時,這變得很明顯。

有沒有人有一個想法,爲什麼會發生這種情況。我希望能夠綁定到ViewModel Firstname,並讓它傳遞給我的person對象。

+0

什麼是您的DataContext?根據代碼我認爲它的viewModel。因此,如果屬性在Person中更改那麼如果使用Just FirstName,則viewModel clas將不會收到通知。所以嘗試在viewModel中觸發PropertyChanged。 –

+0

這就是我如何執行DataContext公共EmployeeAdministrationView(IEmployeeAdministrationViewModel虛擬機):this() DataContext = vm; } –

+0

我認爲我意外地刪除了某人的評論。我很抱歉。他們問我dataContext –

回答

1

如果您的模型更改FirsName值,它將觸發PropertyChanged事件,但不會由ViewModel進行擴展(中繼)。

要使第一個綁定工作,您的ViewModel應該訂閱Person.PropertyChanged,然後在嵌套的FirstName更改時引發自己的事件。

但是,無論如何,Path=Person.FirstName綁定是最好的。

+0

好的,我將只留下與Path = Person.FirstName的綁定。特別是如果它是最好的反正。感謝您的幫助 –

+0

@Bret - 要清楚,它是FirstName的副本是不可取的。並且需要做更多的工作才能做對。 –

+0

我不確定你的意思是通過複製。我只是試圖讓我的視圖模型持有我的財產,這隻會傳遞給person.FirstName使用gets和sets。當視圖模型的FirstName綁定時,該集合完美地工作在文本框中,不會顯示文本。如果我在其中鍵入文本,會更新我的模型,這會讓我感到困惑。 –

0

使用此綁定「Binding Path = Person.FirstName」,View正在監聽PropertyChanged事件的viewModel。視圖不聽你的模型(即Person)。

如果您將View的DataContext設置爲viewModel,那麼爲了讓View知道模型(即人物)的更改,您必須讓viewModel監聽您的PropertyChanged事件模型。然後,從viewModel中引發PropertyChanged事件。