Showing posts with label View Model Constructor. Show all posts
Showing posts with label View Model Constructor. Show all posts

Sunday, February 6, 2011

Using ViewModel in Views (The MVVM way)

The article says how to use one/more ViewMiodels in a View. Also, multiple Views using same ViewModel. Read this post to create a ViewModel.

There are several ways of using ViewModel in a XAML file based on the different scenarios.

Case 1: Initialize a ViewModel without any constructor parameters.

Read this post. This article also expects the reader to be familiar with Expression Blend.

Case 2: Initialize a ViewModel with constructor parameters.

xmlns:local="clr-namespace:****your namespace***"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
<ObjectDataProvider ObjectType="{x:Type local:ViewModel}" x:Key="theViewModel">            <ObjectDataProvider.ConstructorParameters>
<
sys:String>Uday</sys:String>
<
sys:Int32>25</sys:Int32>
</
ObjectDataProvider.ConstructorParameters>
</
ObjectDataProvider>

Notice the System namespace declaration. We can use any data type from System namespace as a constructor parameter. If you have custom data types you can pass them too as a constructor parameter; by declaring namespace in XAML file.


Case 3: In the above two cases, the object can be accessed on the C# side (as a Resource). However, if you update the object in C# side, the ViewModel values are NOT reflected on the XAML side. Now what??!  We can declare a ViewModel object on the C# side and declare it as DataContext for the XAML side. Here is how to do it.

public partial class MainWindow : Window
{
private ViewModel theViewModel = new ViewModel();

public MainWindow()
{
InitializeComponent();
this.DataContext = theViewModel;
}

private void TextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
theViewModel.FirstName = "I am still typing";
}
}

In this way, any updates from XAML side would be seen on C# side too. But, if you use Expression Blend, the ViewModel is not seen in the designer, so you have to write the binding code manually. I wouldn’t suggest this way, but sometime its not up to your choice!