2011-11-01 67 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事件。