Essentially the Idea behind MVVM or Model, View, ViewModel is to remove that code behind and separate out the layers of the application so they can be worked on independently. The interaction between your GUI or View and Viewmodel or codebehind isn't happening like you probably think it is. A lot of people get confused on how the viewmodel actually interacts with the gui or view. I was a winforms dev with the code behind file in which you could easily see event handlers in the code behind and follow the code logically. In your MainWindow Code behind your setting the data context of the XAML gui to the view model like so.
public partial class MainWindow : Window
{
#region Members
SongViewModel _viewModel;
int _count = 0;
#endregion
public MainWindow()
{
InitializeComponent();
// We have declared the view model instance declaratively in the xaml.
// Get the reference to it here, so we can use it in the button click event.
_viewModel = (SongViewModel)base.DataContext;
}
private void ButtonUpdateArtist_Click(object sender, RoutedEventArgs e)
{
++_count;
_viewModel.ArtistName = string.Format("Elvis ({0})", _count);
}
}
Then the {Binding Path=Property} is wiring up your properties of your _viewModel to the XAML Elements. Adding the RaisePropertyChanged is what is notifying the gui that the value of that property has changed.
public string ArtistName
{
get { return Song.ArtistName; }
set
{
if (Song.ArtistName != value)
{
Song.ArtistName = value;
RaisePropertyChanged("ArtistName");
}
}
}
The ArtistName Property of the View model is bound to the label like so in XAML
This is your communication between gui and code more or less. So for instance in your first example when you changed the textbox from 0 to 1, that then updates your ProductID property in your ViewModel. You can see in your ICommand GetProductCommand there is a parameter being passed to relayCommand for ProductID > 0. Now that its 1 canexecute is true so the command is now available to execute and the button becomes clickable. When you Click it GetProduct is the action that takes place and that method then sets your CurrentProduct Property with value. The Datatemplate for product information is bound to ProductModel in the xaml and ProductModel is bound to your CurrentProduct, so now inside that datatemplate the properties of CurrentProduct can be bound to xaml elements so CurrentProduct.ProductName or is bound to
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding ProductName}" />
Its confusing at first but when you get the hang of it, it will make total sense.