• 2 minutes to read

The ViewModelBase class is a BindableBase descendant. It inherits features of the BindableBase class (such as the GetProperty, SetProperty, and RaisePropertyChanged/RaisePropertiesChanged methods) and offers the following additional capabilities:

Initialize properties separately for runtime and design-time modes

A View Model may contain a property that requires access to a database. While you are working in the Visual Studio designer, the View Model is not allowed to connect to the database. This leads to an error in the designer.

In such cases, the ViewModelBase class includes the OnInitializeInDesignMode and OnInitializeInRuntime protected virtual methods, which you can override to initialize properties for runtime and design time modes separately.

public class ViewModel : ViewModelBase {
    public IEnumerable<Employee> Employees {
        get { return GetProperty<IEnumerable<Employee>>(); }
        private set { SetProperty(value); }
    protected override void OnInitializeInDesignMode() {
        Employees = new List<Employee>() {
            new Employee() { Name = "Employee 1" },
    protected override void OnInitializeInRuntime() {
        Employees = DatabaseController.GetEmployees();

Access Services registered within a View

The ViewModelBase class implements the ISupportServices interface that maintains the Services mechanism. The ViewModelBase.GetService method, which employs the ISupportServices interface, allows you to access services registered in a View.

<UserControl x:Class="WinUIViewModelBase.View" 
             xmlns:ViewModel="using:WinUIViewModelBase.ViewModel" ...> 
public class ViewModel : ViewModelBase {
    public IMessageBoxService MessageBoxService { get { return GetService<IMessageBoxService>(); } }