I am having a problem with the textbox text updating in my view. I have seen some other threads but cannot find one that is close to my setup.
I have a model with a class of
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"));
}
}
}
This is what my viewModel Looks Like
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 Binding Setup
// 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}"
So if i bind to the Person.First Name everything works great. If I bind to FirstName then it will update my model fine but will not get the data for The TextBox Text. This becomes apparent when i select an item in my list.
Does anyone have an idea why this would happen. I want to be able to bind to the ViewModel Firstname and just have it pass that to my person object.
If your model changes the FirsName value it triggers an PropertyChanged event but that is not extended (relayed) by the ViewModel.
To make the first binding work your ViewModel should subscribe to Person.PropertyChanged and then raise its own event when the nested FirstName changes.
But of course the
Path=Person.FirstNamebinding is preferable anyway.