Skip to main content

Services in ViewModelBase Descendants

  • 2 minutes to read

The ViewModelBase class implements the ISupportServices interface, which 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="ViewModelBaseSample.View" 
             xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm" 
             xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
             xmlns:ViewModels="clr-namespace:ViewModelBaseSample.ViewModels" ...> 
    <UserControl.DataContext> 
        <ViewModels:ViewModel/> 
    </UserControl.DataContext> 
    <dxmvvm:Interaction.Behaviors>
        <dx:DXMessageBoxService/>
    </dxmvvm:Interaction.Behaviors>
    ...
</UserControl>
public class ViewModel : ViewModelBase {
    public IMessageBoxService MessageBoxService { get { return GetService<IMessageBoxService>(); } }
}

If it is necessary to use several services of the same type, assign the Name property for these services and access a specific service by its name.

<UserControl x:Class="ViewModelBaseSample.View" 
             xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
             xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm" 
             xmlns:ViewModels="clr-namespace:ViewModelBaseSample.ViewModels" ...> 
    <UserControl.DataContext> 
        <ViewModels:ViewModel/> 
    </UserControl.DataContext> 
    <dxmvvm:Interaction.Behaviors>
        <dx:DXMessageBoxService x:Name="service1"/>
        <dx:DXMessageBoxService x:Name="service2"/>
    </dxmvvm:Interaction.Behaviors>
    ...
</UserControl>
public class ViewModel : ViewModelBase {
    public IMessageBoxService MessageBoxService1 { get { return GetService<IMessageBoxService>("service1"); } }
    public IMessageBoxService MessageBoxService2 { get { return GetService<IMessageBoxService>("service2"); } }
}

View Models can be related to each other with the parent-child relationship. This is achieved with the ISupportParentViewModel interface. You can pass the main View Model to the child using the ISupportParentViewModel.ParentViewModel property. This allows the child View Model to access Services that are registered for the main View Model. Please review the following topic for more information about this mechanism: ViewModel relationships (ISupportParentViewModel).

Here is an example that demonstrates the use of services when View Models derived from the ViewModelBase class are related to each other with the parent-child relationship: DXMessageBoxService.