I have a real simple example that works nicely without a viewmodel as i have a Item class that implements iNotifyPropertyChanged
public class Item : INotifyPropertyChanged
{
private string _name;
private string _desc;
public string Name
{
get
{ return _name; }
set
{
if (_name == value)
return;
_name = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("Name"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public Item()
{
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, e);
}
}
This works in a simple example where I have the following code behind:
public MainPage()
{
InitializeComponent();
item = new Item() { Name = "john", Description = "this is my name" };
LayoutRoot.DataContext = item;
}
and if I have a button that calls a command handler in the code behind I see changes to the simple UI as propertychanged event is being "listened" to as a result of the Twoway binding on my text property. the handler looks like:
private void Button_Click(object sender, RoutedEventArgs e)
{
item.Name = "ted";
item.Description = "adddress";
}
so of course this changes the UI (I said this is real simple example) Now I introduce a Viewmodel and the changes to the simple model are not reflected as there is no one listening for the propertychanged.
I set the datacontext in the view to the viewmodel , infact this is the only line of code in the view : LayoutRoot.DataContext = new MyViewModel();
Now my Viewmodel looks like:
public class MyViewModel
{
Item item = null;
public ICommand ChangeCommand { get; private set; }
public MyViewModel()
{
item = new Item() { Name = "john", Description = "jjjj" };
ChangeCommand = new DelegateCommand<string>(OnChange);
}
private void OnChange(string title)
{
item.Name = "bill";
}
Notes: I use the Patterns and practices commanding to fire the event from the XAML to Viewmodel and this works great
My handler again changes the item.name which results in the setter being called and the this.OnPropertyChanged(new PropertyChangedEventArgs("Name")); being called but no one is listening so no changes are made.
I am trying to keep this example real simple and some will say too simple but I just want to know why the binding is not working. I can pull from the view to viewmodel but I need to able to do the reverse. Am wondering what point I am missing.