Skip to content

ViewModel

François edited this page Sep 7, 2022 · 2 revisions

Description

The ViewModel is actually the code file that is attached to the View. It is what we call for him, the DataContext. In this DataContext, we will find the properties used in the XAML View but also the commands and some other methods.

A class defining the ViewModel of a View (DataContext) is necessarily derived from the abstract ViewModel class. In the TextUserVM.cs file, we therefore have for class signature:

internal class TextUserVM: ViewModel

Properties

It can be defined in two different ways:

private string _contentText;

public string ContentText
{
    get { return Get(ref _contentText); }
    set { Set(ref _contentText, value); }
}

The Getter of this property returns the value of the static variable by reference. The Setter will assign the value to it, but also trigger a NotifyPropertyChanged event for it.

private string _contentText;

public string ContentText
{
    get { return _contentText); }
    set {
           _contentText = value);
           NotifyPropertyChanged("ContentText");
        }
}

In this last code snippet, the getter and setter does not use the Get and Set methods defined in the View Model class and if the need is to emit the event, it will have to be done manually.

Command

The commands are defined as follows in the view model.

private ICommand _showText;

public ICommand ShowText
{
    get { return _showText?? ( _showText = new CommandHandler(ShowTextCommand)); }
}

private void ShowTextCommand(object obj)
{
    MessageBox.Show(ContentText);
}

By need here setter to define the command. It is a property that returns an action generated by the CommandHandler class in connection with the method which will execute the necessary code at the time of its call.

Initialization

There can be an overload method for Initialize with or without parameters. This method, if used, can be automatically executed and parameterized when creating the View-ViewModel set via the Factory.

Other

The View Model gives access to the View to which it is attached. The XAML file, once created and instantiated, is saved in the View property of the View Model class. It is then possible to access the XAML elements defined by their name or other.

For example, to access the view element for TextUser.xaml, it is enough in the ViewModel to have a call with Cast like this:

var view = ((TextUser)View);

The ViewModel also has a set of events common to all ContentControls. In general, a UserControl will be used as in the example file TextUser.xaml. But any control derived from ContentControl will do fine too.

Clone this wiki locally