ViewModelBase

  • 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() {
        base.OnInitializeInDesignMode();
        Employees = new List<Employee>() {
            new Employee() { Name = "Employee 1" },
        };
    }
    protected override void OnInitializeInRuntime() {
        base.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:dxmvvmi="using:DevExpress.WinUI.Mvvm.UI.Interactivity"
             xmlns:dxmvvm="using:DevExpress.WinUI.Mvvm.UI"
             xmlns:ViewModel="using:WinUIViewModelBase.ViewModel" ...> 
    <UserControl.DataContext>
        <ViewModel:ViewModel/>
    </UserControl.DataContext>
    <dxmvvmi:Interaction.Behaviors>
        <dxmvvm:MessageBoxService/>
    </dxmvvmi:Interaction.Behaviors>
    ...
</UserControl>
public class ViewModel : ViewModelBase {
    public IMessageBoxService MessageBoxService { get { return GetService<IMessageBoxService>(); } }
}