-
-
Notifications
You must be signed in to change notification settings - Fork 1
ViewModel
Grega Mohorko edited this page Dec 21, 2017
·
3 revisions
- 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
)
- Name it [TheNameOfTheUserControl]ViewModel (in this case:
- Set the base class to
ViewModel
(fromGM.WPF.MVVM
)
- Add a new class to the same namespace where your UserControl is located
using GM.WPF.MVVM;
namespace MyWpfApplication
{
class MyUserControlViewModel : 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.
Copyright (c) 2018 Gregor Mohorko