Back to Devexpress

Use the MVVM Framework to Avoid Code-Behind

wpf-404269-mvvm-framework-use-the-mvvm-framework-to-avoid-code-behind.md

latest7.0 KB
Original Source

Use the MVVM Framework to Avoid Code-Behind

  • Jan 31, 2023
  • 5 minutes to read

This topic describes the most common scenarios where the DevExpress MVVM Framework can help you avoid code-behind and maintain a clean MVVM pattern in your application.

Process UI Element Events in the View Model

You can specify a View Model command that is executed when a UI element raises an event. To do this, create a command in your View Model and implement one of the techniques below.

Use the EventToCommand Behavior

Assign an EventToCommand behavior to the UI element. In this behavior, specify the EventName / Event property and bind the created command to the Command property:

xaml
<UserControl>
    <!-- ... -->
    <dxmvvm:Interaction.Behaviors>
        <dxmvvm:EventToCommand EventName="Loaded" Command="{Binding InitializeCommand}"/>
    </dxmvvm:Interaction.Behaviors>
</UserControl>
csharp
public class ViewModel : ViewModelBase {
    [Command]
    public void Initialize() {
        // ...
    }
}
vb
Public Class ViewModel
    Inherits ViewModelBase

    <Command>
    Public Sub Initialize()
        ' ...
    End Sub
End Class

View Example: How to Use EventToCommand

Use the CommandParameter property to pass a parameter to the command. The PassEventArgsToCommand and EventArgsConverter properties allow you to pass event arguments to the command.

Use Built-in Command Properties

The DevExpress Data Grid contains command properties that correspond to events. This is one of the ways how we extend MVVM support. If the UI element contains a command property (for example, the TableView.RowDoubleClickCommand for the TableView.RowDoubleClick event), bind this property to your View Model command:

xaml
<dxg:GridControl.View>
    <dxg:TableView RowDoubleClickCommand="{Binding RowDoubleClickCommand}"/>
</dxg:GridControl.View>
csharp
public class ViewModel : ViewModelBase {
    // ...
    [Command]
    public void RowDoubleClick(RowClickArgs args) {
        DXMessageBox.Show("Row double click: " + ((DataItem)args.Item).Name);
    }
}
vb
Public Class ViewModel
    Inherits ViewModelBase
    ' ...
    <Command>
    Public Sub RowDoubleClick(ByVal args As RowClickArgs)
        Call DXMessageBox.Show("Row double click: " & CType(args.Item, DataItem).Name)
    End Sub
End Class

View Example: Handle Row Double-clicks in an MVVM Application

Refer to the following help topic for the complete command list: Data Grid Command API.

Handle Events Outside of the View Model

You can maintain an MVVM pattern even if you cannot process UI element events in the View Model. For example, you may need to access properties of event arguments (e.Handled, e.Cancel, and so on).

Create a Behavior class and attach it to the UI element. Override the OnAttached method and subscribe to the event. Unsubscribe from the event in the overloaded OnDetaching method:

xaml
<TextBox Text="Text">
    <dxmvvm:Interaction.Behaviors>
        <behaviors:ValidationBehavior ValidForeground="{Binding ValidBrush}"
                                      InvalidForeground="{Binding InvalidBrush}"
                                      InvalidValue="{Binding InvalidValue}"/>
    </dxmvvm:Interaction.Behaviors>
</TextBox>
csharp
public class ValidationBehavior : Behavior<TextBox> {
    // ...
    protected override void OnAttached() {
        base.OnAttached();
        AssociatedObject.TextChanged += OnAssociatedObjectTextChanged;
    }
    void OnAssociatedObjectTextChanged(object sender, TextChangedEventArgs e) {
        // ...
    }
    protected override void OnDetaching() {
        AssociatedObject.TextChanged -= OnAssociatedObjectTextChanged;
        base.OnDetaching();
    }
}
vb
Public Class ValidationBehavior
    Inherits Behavior(Of TextBox)
    ' ...
    Protected Overrides Sub OnAttached()
        MyBase.OnAttached()
        AddHandler AssociatedObject.TextChanged, AddressOf OnAssociatedObjectTextChanged
    End Sub

    Private Sub OnAssociatedObjectTextChanged(ByVal sender As Object, ByVal e As TextChangedEventArgs)
        ' ...
    End Sub

    Protected Overrides Sub OnDetaching()
        RemoveHandler AssociatedObject.TextChanged, AddressOf OnAssociatedObjectTextChanged
        MyBase.OnDetaching()
    End Sub
End Class

View Example: Create a Custom Attached Behavior

Refer to the following help topic for more information: Behaviors.

Handle Events in the View

The DXEvent extension allows you to create a simple event handler in the View:

xaml
<dxg:TableView ...
               CompleteRecordDragDrop="{DXEvent Handler='@args.Handled = true'}"/>

Refer to the following help topic for more information on the DXEvent syntax: Language Specification.

Call UI Element Methods from the View Model

  1. Implement a Service that calls the UI element’s methods:

  2. Attach this service to the UI element:

  3. In the View Model, obtain the service and call the service’s methods:

View Example: Update Data in a Separate Thread

Refer to the following help topic for more information: Create a Custom Service.

See Also

EventToCommand

Behaviors

DXEvent

Services