Skip to content

ViewModel

Grega Mohorko edited this page Dec 21, 2017 · 3 revisions

Creating a ViewModel

  • To create a ViewModel for MyUserControl:
    • Add a new class to the same namespace where your UserControl is located
      • Name it [TheNameOfTheUserControl]ViewModel (in this case: MyUserControlViewModel)
    • Set the base class to ViewModel (from GM.WPF.MVVM)
using GM.WPF.MVVM;

namespace MyWpfApplication
{
    class MyUserControlViewModel : ViewModel
    {
        // ...
    }
}

Using the ViewModel

  • In the MyUserControl constructor, set the property ViewModel to an instance of your ViewModel class
public MyUserControl()
{
    InitializeComponent();
    
    var vm = new MyUserControlViewModel();
    ViewModel = vm;
}

You can get the ViewModel later like this:

var vm = (MyUserControlViewModel)ViewModel;
  • [optional] In the MyUserControl.xaml file, add this attribute to the opening tag: d:DataContext="{d:DesignInstance Type=local:MyUserControlViewModel, IsDesignTimeCreatable=True}"

If your ViewModel implements IDisposable and is used inside the BaseControl or BaseWindow, it will automatically be disposed when the window closes.

Clone this wiki locally