POCO ViewModels

  • 13 minutes to read

POCO (Plain Old CLR Objects) View Models simplify and speed up the development process.

POCO View Models allow you to:

  • define bindable properties as simple auto-implemented properties;
  • create methods that function as commands at runtime;
  • make properties and methods implement MVVM-specific interfaces.

This allows you to create clean, simple, maintainable, and testable MVVM code.

The POCO View Models are fully compatible with any WPF control.

Basics of Generating POCO View Models

A POCO class does not implement an interface, and does not need to be inherited from a base class, such as ViewModelBase or BindableBase. To transform a POCO class into a fully functional ViewModel, create a class instance with the DevExpress.Mvvm.POCO.ViewModelSource.Create method. See the example below.

public class LoginViewModel {
    //This property will be converted to a bindable one
    public virtual string UserName { get; set; }

    //SaveAccountSettingsCommand will be created for the SaveAccountSettings and CanSaveAccountSettings methods:
    //SaveAccountSettingsCommand = new DelegateCommand<string>(SaveAccountSettings, CanSaveAccountSettings);
    public void SaveAccountSettings(string fileName) {
        //...
    }
    public bool CanSaveAccountSettings(string fileName) {
        return !string.IsNullOrEmpty(fileName);
    }

    //We recommend that you not use public constructors to prevent creating the View Model without the ViewModelSource
    protected LoginViewModel() { }
    //This is a helper method that uses the ViewModelSource class for creating a LoginViewModel instance
    public static LoginViewModel Create() {
        return ViewModelSource.Create(() => new LoginViewModel());
    }
}

You can use the ViewModelSource class to create a View Model instance in XAML.

<UserControl x:Class="DXPOCO.Views.LoginView"
    xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm"
    xmlns:ViewModels="clr-namespace:DXPOCO.ViewModels"
    DataContext="{dxmvvm:ViewModelSource Type=ViewModels:LoginViewModel}"
    ...>
    <Grid>
        <!--...-->
    </Grid>
</UserControl>

The ViewModelSource.Create method uses Reflection Emit to create a descendant of the specified ViewModel class and returns the descendant class instance at runtime. The code below is similar to the one that the ViewModelSource generates based on the LoginViewModel class.

public class LoginViewModel_EXTENSION : LoginViewModel, INotifyPropertyChanged {
    public override string UserName {
        get { return base.UserName; }
        set {
            if(base.UserName == value) return;
            base.UserName = value;
            RaisePropertyChanged("UserName");
        }
    }
    DelegateCommand<string> saveAccountSettingsCommand;
    public DelegateCommand<string> SaveAccountSettingsCommand {
        get {
            return saveAccountSettingsCommand ?? 
                (saveAccountSettingsCommand = 
                new DelegateCommand<string>(SaveAccountSettings, CanSaveAccountSettings));
        }
    }

    //INotifyPropertyChanged Implementation
}

Pass Parameters to the ViewModel Constructor

You can pass parameters to the ViewModel's constructor using any of the following approaches.

  • Use lambda expressions. Lambda expressions work slower, because they are not cached and are newly compiled with each method call.

    ViewModelSource.Create(() => new LoginViewModel(caption: "Login") {
        UserName = "John Smith"
    });
    
  • Use delegates. This approach works faster than lambda expressions, because the compiled delegate instances can be cached. This is the quickest approach for passing parameters to the ViewModel constructor.

    var factory = ViewModelSource.Factory((string caption) => new LoginViewModel(caption));
    factory("Login");
    

This example demonstrates how to use the POCO mechanism to create view models.

Imports System.Windows.Controls

Namespace Example.View
    Partial Public Class LoginView
        Inherits UserControl

        Public Sub New()
            InitializeComponent()
        End Sub
    End Class
End Namespace

Bindable Properties

The POCO mechanism generates bindable properties for properties that meet all the following requirements:

  1. The property is public and auto-implemented.

    and

  2. The property has the virtual (C#) or Overridable (VB) modifier.

    and

  3. The property has a public getter, and a protected or public setter.
    TIP

    If the property has no setter, you can use the RaisePropertyChanged extension method to explicitly raise the PropertyChanged event for this property. Refer to the GitHub example for more information on how to use the RaisePropertyChanged extension method to explicitly raise the PropertyChanged event.

You can define methods that are invoked when properties are changed. These method names should use the following formats: On[PropertyName]Changed and On[PropertyName]Changing.

public class LoginViewModel {
        public virtual string UserName { get; set; }
        protected void OnUserNameChanged() {
            //...
        }
    }

    public class LoginViewModel {
        public virtual string UserName { get; set; }
        protected void OnUserNameChanged(string oldValue) {
            //...
        }
        protected void OnUserNameChanging(string newValue) {
            //...
        }
    }

You can use the BindableProperty attribute to:

  • prevent the POCO mechanism from generating a bindable property for a specified property;
  • specify which method should be invoked when a property value is changing or has been changed. This is useful when the method's name does not match the On[PropertyName]Changed and On[PropertyName]Changing convention.
public class LoginViewModel {
        [BindableProperty(isBindable: false)]
        public virtual bool IsEnabled { get; set; }

        [BindableProperty(OnPropertyChangedMethodName = "Update")]
        public virtual string UserName { get; set; }
        protected void Update() {
            //...
        }
    }

You can use the Fluent API to control POCO ViewModel generation.

[MetadataType(typeof(Metadata))]
public class LoginViewModel {
    public class Metadata : IMetadataProvider<LoginViewModel> {
        void IMetadataProvider<LoginViewModel>.BuildMetadata
            (MetadataBuilder<LoginViewModel> builder) {

            builder.Property(x => x.UserName).
                OnPropertyChangedCall(x => x.Update());
            builder.Property(x => x.IsEnabled).
                DoNotMakeBindable();
        }
    }
    public virtual bool IsEnabled { get; set; }
    public virtual string UserName { get; set; }
    protected void Update() {
        //...
    }
}

Commands

The POCO mechanism generates commands for all public methods without parameters or with a single parameter. You can use the Command attribute or the Fluent API to control the command generation mechanism.

public class LoginViewModel {
    [Command(isCommand: false)]
    public void SaveCore() {
        //...
    }

    [Command(CanExecuteMethodName = "CanSaveAccountSettings",
        Name = "SaveCommand",
        UseCommandManager = true)]
    public void SaveAccountSettings(string fileName) {
        //...
    }
    public bool CanSaveAccountSettings(string fileName) {
        return !string.IsNullOrEmpty(fileName);
    }
}

[MetadataType(typeof(Metadata))]
public class LoginViewModel {
    public class Metadata : IMetadataProvider<LoginViewModel> {
        void IMetadataProvider<LoginViewModel>.BuildMetadata(MetadataBuilder<LoginViewModel> builder) {
            builder.CommandFromMethod(x => x.SaveCore()).
                DoNotCreateCommand();
            builder.CommandFromMethod(x => x.SaveAccountSettings(default(string))).
                CanExecuteMethod(x => x.CanSaveAccountSettings(default(string))).
                CommandName("SaveCommand");
        }
    }
    public void SaveCore() {
        //...
    }
    public void SaveAccountSettings(string fileName) {
        //...
    }
    public bool CanSaveAccountSettings(string fileName) {
        return !string.IsNullOrEmpty(fileName);
    }
}

To update an automatically generated command in a POCO View Model, use the RaiseCanExecuteChanged extension method available from the DevExpress.Mvvm.POCO.POCOViewModelExtensions class.

[POCOViewModel]
public class ViewModel {
    public void GoBack(){
        //...
    }
    public bool CanGoBack(){
        //...
    }
    public void UpdateSaveCommand(){
        this.RaiseCanExecuteChanged(c => c.GoBack());
    }
}

Refer to the Commands topic for more information.

Services

The DevExpress MVVM Framework provides the Services mechanism. The code sample below demonstrates how to access the Message Box service.

using DevExpress.Mvvm.POCO;
...
public class LoginViewModel {
    public IMessageBoxService MessageBoxService { get { return this.GetService<IMessageBoxService>(); } }
}

Review the Services in POCO objects topic for more information about accessing services.

View Model Parent-Child Relationships

POCO View Models can relate to each other with the parent-child relationship. This is achieved with the ISupportParentViewModel interface that is automatically implemented when you create a POCO object with the ViewModelSource class. With this interface, child View Models may access Services registered in the main View Model. The ViewModel relationships (ISupportParentViewModel) topic contains more information on how to set the parent-child relationship and its advantages.

Automatic IDataErrorInfo Implementation

The IDataErrorInfo interface is the standard mechanism for data validation in WPF. You can use this interface to provide validation rules for each individual property or for the entire object. The POCO mechanism allows you to automatically implement the IDataErrorInfo interface based on defined attributes or Fluent API.

To enable this feature, apply the POCOViewModel attribute for your View Model and set the POCOViewModel.ImplementIDataErrorInfo parameter to True.

//Attribute-based approach
[POCOViewModel(ImplementIDataErrorInfo = true)] 
public class LoginViewModel { 
    [Required(ErrorMessage = "Please enter the user name.")] 
    public virtual string UserName { get; set; }
}

//Fluent API
[POCOViewModel(ImplementIDataErrorInfo = true)]
[MetadataType(typeof(LoginViewModel.Metadata))]
public class LoginViewModel {
   public class Metadata : IMetadataProvider<LoginViewModel> {
       void IMetadataProvider<LoginViewModel>.BuildMetadata(MetadataBuilder<LoginViewModel> builder) {
           builder.Property(x => x.UserName).
               Required(() => "Please enter the user name.");
        }
    }
    public virtual string UserName { get; set; }
}

When the ViewModelSource generates a descendant of a View Model, it implements the IDataErrorInfo interface as follows.

public class LoginViewModel : IDataErrorInfo { 
    ... 
    string IDataErrorInfo.Error { 
        get { return string.Empty; } 
    } 
    string IDataErrorInfo.this[string columnName] { 
        get { return IDataErrorInfoHelper.GetErrorText(this, columnName); } 
    } 
}

The IDataErrorInfoHelper class allows you to get an error based on specified DataAnnotation attributes or Fluent API.

The code example below demonstrates how to use the POCO mechanism to implement the IDataErrorInfo interface.

using DevExpress.Mvvm;
using DevExpress.Mvvm.DataAnnotations;
using System.Windows.Media;

namespace Example.ViewModel {
    [POCOViewModel(ImplementIDataErrorInfo = true)]
    public class MainViewModel : ViewModelBase {
        static PropertyMetadataBuilder<MainViewModel, string> AddPasswordCheck(PropertyMetadataBuilder<MainViewModel, string> builder) {
            return builder.MatchesInstanceRule((name, vm) => vm.Password == vm.ConfirmPassword, () => "The passwords don't match.")
                .MinLength(8, () => "The password must be at least 8 characters long.")
                .MaxLength(20, () => "The password must not exceed the length of 20.");
        }
        public static void BuildMetadata(MetadataBuilder<MainViewModel> builder) {
            builder.Property(x => x.FirstName)
                .Required(() => "Please enter the first name.");
            builder.Property(x => x.LastName)
                .Required(() => "Please enter the last name.");
            builder.Property(x => x.Email)
                .EmailAddressDataType(() => "Please enter a correct email address.");
            AddPasswordCheck(builder.Property(x => x.Password))
                .Required(() => "Please enter the password.");
            AddPasswordCheck(builder.Property(x => x.ConfirmPassword))
                .Required(() => "Please confirm the password.");
        }
        public virtual string FirstName { get; set; }
        public virtual string LastName { get; set; }
        public virtual string Email { get; set; }
        public virtual string Password { get; set; }
        public virtual string ConfirmPassword { get; set; }
        public void OnPasswordChanged() {
            this.RaisePropertyChanged(() => ConfirmPassword);
        }
        public void OnConfirmPasswordChanged() {
            this.RaisePropertyChanged(() => Password);
        }
    }
}

If you need to extend the default IDataErrorInfo implementation, you can manually implement the IDataErrorInfo interface and use the IDataErrorInfoHelper class.