Friday, 9 December 2016

In this post we are going to see how to create Sample MVVM Application in WPF with ICommand , INotificationChanged, ObservationCollection Implementation For this first we have to create a class which implements the ICommand, name it as Relaycommand, then Create a ViewModelBase class , Then derive it in ViewModels

From the above code you may notice that one command have input paramter , another one not, so let us see how to use this relay command , first we have to create the instance of the Relaycommand like below

This follows the DataTemplate model to place the view, see the main view code , how the template is binding with ViewHere in the main view you can see that the View is binded against the model, when ever the model is loaded , corresponding view will be bind using DataTemplate, in DataTemplate we have to say , for this viewmodel, this view must load, For this to work we have to use the ContentControl, where we have to use the CurrentViewmodel property to change the view

MainWindow.xaml

**********************

<Window x:Class="Sample.MainWindow"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:Employees="clr-namespace:Sample.Employees"

xmlns:local="clr-namespace:Sample"

Title="MainWindow" Height="300"
Width="300">

<Window.DataContext>

<local:MainWindowViewModel />

</Window.DataContext>

<Window.Resources>

<DataTemplate DataType="{x:Type Employees:EmployeeListViewModel}">

<Employees:EmployeeListView />

</DataTemplate>

<DataTemplate DataType="{x:Type Employees:EmployeeViewModel}">

<Employees:AddEditEmployeeView />

</DataTemplate>

</Window.Resources>

<Grid>

<Grid.RowDefinitions>

<RowDefinition
Height="Auto"
/>

<RowDefinition
Height="*" />

</Grid.RowDefinitions>

<Grid Grid.Row="0" x:Name="NavBar">

<Grid.ColumnDefinitions>

<ColumnDefinition Width="*"/>

<ColumnDefinition Width="*"/>

<ColumnDefinition Width="*"/>

</Grid.ColumnDefinitions>

<Button Command="{Binding NavCommand}" CommandParameter="Employees"

Grid.Column="0"
Content="Employee
List" />

<Button
Command="{Binding NavCommand}" CommandParameter="EditEmp"

Grid.Column="2"
Content="Edit Employees"
/>

</Grid>

<Grid Grid.Row="1" x:Name="MainContent">

<ContentControl Content="{Binding
CurrentViewModel}"
/>

</Grid>

</Grid>

</Window>

Here in MainViewModel you can see that the Navigation is done by CurrentViewModel

ManiViewModel is binded in DataContext of the View so when MainViewModel Loadeds it will bind everything, Based on the Button click , Corresponding ViewModel instance is created and Bind to the CurrentViewModel, when this Viewmodel loades the Corresponding View get load using the ContentControl and DataTemplate