Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Business Scenario
The main window of the Basic MVVM Application QuickStart represents a subset of a
survey application. In this window, an empty survey with different types of
Implementation Details
The QuickStart highlights the key elements and considerations to implement the
MVVM pattern in a basic application.
<Grid x:Name="LayoutRoot"
Background="{StaticResource MainBackground}">
<Grid MinWidth="300" MaxWidth="800">
...
<views:QuestionnaireView Grid.Row="1"
DataContext="{Binding QuestionnaireViewModel}"
Height="246" VerticalAlignment="Top">
</views:QuestionnaireView>
...
</Grid>
</Grid>
</Window>
In order to populate this child view with its corresponding view model, its
DataContext is set to a property of the MainWindow's view model that contains
an instance of the child QuestionnaireView's view model.
Note: The view model class typically derives from the BindableBase class. In
some cases, the model can derive from BindableBase, when the property that
needs to update the view when its value is changed is stored in the model.
To support INotifyPropertyChanged, your class needs to derive from the
BindableBase class, and the property setter needs to call the SetProperty
method of the BindableBase class.
The following code shows how the BindableBase class implements the
INotifyPropertyChanged interface. Note that the SetProperty method updates
the propertys value and fires the PropertyChanged event when a property
changes its value. Alternatively, you can use the OnPropertyChanged method,
passing a lambda expression that references the property, to fire the
PropertyChanged event. This is useful for when one property update triggers
another property update. And also provides backward compatibility with the
previous version of Prism.
C#
public abstract class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName]
string propertyName = null)
{
if (object.Equals(storage, value)) return false;
storage = value;
this.OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged(string propertyName)
{
var eventHandler = this.PropertyChanged;
if (eventHandler != null)
{
eventHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
protected void OnPropertyChanged<T>(Expression<Func<T>>
propertyExpression)
{
var propertyName =
PropertySupport.ExtractPropertyName(propertyExpression);
this.OnPropertyChanged(propertyName);
}
}
The method is used so that when the questionnaire property changes its value and
updates the user interface. In any view where the data might change in the view
model and you want those changes to be reflected on the screen, you need to
implement this pattern for all the properties in the view model.
The questionnaire property, the collection property, and the command property are
initialized in the view model class constructor.
C#
public QuestionnaireViewModel()
{
this.questionnaire = new Questionnaire();
this.AllColors = new[] { "Red", "Blue", "Green" };
}
To keep the solution simple, this handler method returns the values entered for the
questions to the Output window in Visual Studio with the help of a helper method
that is already implemented in the view model class. A real implementation of a
command handler would typically do something like call out to a service to save the
results to a repository or retrieve data if it was a Load type of operation. It might
also cause navigation to another view to occur by calling to a navigation service.
Element name
Property
Value
NameTextBox
Text
AgeTextBox
Text
Question1Response
Text
ColorRun
Foreground
Colors
ItemsSource
{Binding Path=AllColors}
Colors
SelectedItem
SubmitButton
Command
{Binding SubmitCommand}
ResetButton
Command
{Binding ResetCommand}
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:basicMvvmQuickstartDesktop="clrnamespace:BasicMVVMQuickstart_Desktop"
xmlns:viewModel="clrnamespace:Microsoft.Practices.Prism.Mvvm;assembly=Microsoft.Practices.Prism.Mvv
m.Desktop"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:views="clr-namespace:BasicMVVMQuickstart_Desktop.Views"
mc:Ignorable="d"
Title="Basic MVVM Quickstart"
Height="350"
Width="525"
d:DataContext="{d:DesignInstance
basicMvvmQuickstartDesktop:QuestionnaireViewDesignViewModel,
IsDesignTimeCreatable=True}"
viewModel:ViewModelLocator.AutoWireViewModel="True">
Prism's view model locator is an attached property that when set to true it will try to
locate the view model of the view, and then set the view's data context to an
instance of the view model. To locate the corresponding view model, the view model
locator uses two approaches. First it will look for the view model in a view
name/view model registration mapping. If a registration is not found, it will fall back
to a convention-based approach, that will locate the view models, by replacing
.View from the view namespace with .ViewModel and appending ViewModel
to the views name. For more information about ways to hook up views to view
models; see "Implementing the MVVM Pattern."
Note that you need to specify the class that will be used as the DesignInstance,
and then set the IsDesignTimeCreatable property to true. The design view model
class used as DesignInstance is a class that must have a default constructor.
You can see how the design view model for the QuickStart is defined, in the
following code:
C#
public class QuestionnaireViewDesignViewModel
{
public QuestionnaireViewDesignViewModel()
{
this.QuestionnaireViewModel = new QuestionnaireViewModel();
}
public QuestionnaireViewModel QuestionnaireViewModel { get; set; }
}
This design view model just has to initialize the properties used in the view for
binding and populate them with mock data. As it is used only for design, it is not
necessary to derive from BindableBase, nor implement the
INotifyPropertyChanged interface.
More Information
For more information about implementing the MVVM pattern, see the following
topics:
Implementing the MVVM Pattern
Advanced MVVM Scenarios
To learn about other code samples included with Prism, see the following topics:
Stock Trader Reference Implementation
Modularity QuickStarts
Interactivity QuickStart
Commanding QuickStart
UI Composition QuickStart
State-Based Navigation QuickStart
View-Switching Navigation QuickStart
Event Aggregation QuickStart