Behaviors
- 8 minutes to read
Behaviors add extra functionality to an object without modifying it. For instance, a close button closes a tab or a form and additionally displays a confirmation dialog. You can use behaviors in MVVM applications to accomplish this.
Confirmation Behavior
Note
MVVM Best Practices Demo The text below has a related example in the DevExpress ‘MVVM Best Practices’ demo.
Group: API Code Examples
Module: Behaviors
Example: Simple Behaviors
24.1 Demo Center: Launch the demo
A simple confirmation behavior can only be attached to a cancelable event (for example, form closing or edit value changing). To implement custom behavior, define a class that derives from the ConfirmationBehavior class. It contains two virtual string properties for the confirmation message box’s title and text. Override these properties to assign your text strings. The class constructor should inherit the base class constructor with a parameter equal to the name of the event that triggers this behavior.
public class FormCloseBehavior : ConfirmationBehavior<FormClosingEventArgs> {
public FormCloseBehavior() : base("FormClosing") { }
protected override string GetConfirmationCaption() {
return "Confirm exit";
}
protected override string GetConfirmationText() {
return "Do you really want to exit the application?";
}
}
Tip
The ConfirmationBehavior class’s last virtual property is the boolean Confirm property. You can also override it to specify the related event’s cancel conditions.
Use the MvvmContext component’s API to attach this behavior to the target UI element.
You can simplify this process by moving the behavior declaration from a separate class to a generic one.
mvvmContext1.AttachBehavior<ConfirmationBehavior<ChangingEventArgs>>(checkEdit1, behavior => {
behavior.Caption = "CheckEdit State Changing";
behavior.Text = "This checkEdit's checked-state is about to be changed. Are you sure?";
behavior.Buttons = ConfirmationButtons.YesNo;
behavior.ShowQuestionIcon = true;
}, "EditValueChanging");
Fluent API is also supported.
mvvmContext1.WithEvent<ChangingEventArgs>(checkEdit1, "EditValueChanging").Confirmation(behavior => {
behavior.Caption = "CheckEdit State changing";
behavior.Text = "This checkEdit's checked-state is about to be changed. Are you sure?";
});
Event-To-Command Behaviors
Note
MVVM Best Practices Demo The text below has a related example in the DevExpress ‘MVVM Best Practices’ demo.
Group: API Code Examples
Module: Behaviors
Example: Event-To-Command Behavior
24.1 Demo Center: Launch the demo
Event-to-command behaviors fit all the remaining events if a confirmation behavior requires an event that receives CancelEventArgs type arguments. This behavior binds a command to a target UI element, and when this element fires the required event, the command executes. This can be used for:
- Third-party UI elements that do not implement the ISupportCommandBinding interface and thus cannot be bound using the MvvmContext component’s API (the mvvmContext.BindCommand method);
- DevExpress controls that require extra functionality. For instance, if you need a SimpleButton to do something on the MouseHover event.
Event-to-command behaviors are implemented similarly to confirmation behaviors: you need to define a separate class that derives from the DevExpress EventToCommandBehavior class. In the class constructor, specify the target event name and the command that should be executed on this event.
public class ClickToSayHello : DevExpress.Utils.MVVM.EventToCommandBehavior<ViewModel, EventArgs> {
public ClickToSayHello()
: base("Click", x => x.SayHello()) {
}
}
Attaching event-to-command behaviors is identical to confirmation behaviors.
Fluent API allows you to implement event-to-command behaviors without creating separate classes.
mvvmContext.WithEvent<ViewModel, EventArgs>(thirdPartyButton, "Click").EventToCommand(x => x.SayHello());
Key-To-Command and Keys-To-Command Behaviors
Note
MVVM Best Practices Demo The text below has a related example in the DevExpress ‘MVVM Best Practices’ demo.
Group: API Code Examples
Module: Behaviors
Example: Key-To-Command and Keys-To-Command Behaviors
24.1 Demo Center: Launch the demo
These behaviors allow you to execute commands when end-users press specific keyboard keys.
Binding a single keyboard shortcut
The sample ViewModel below defines the “OnAKey” and “OnAltKey” commands that display service-based notifications.
public class KeyAwareViewModel {
protected IMessageBoxService MessageBoxService {
get { return this.GetService<IMessageBoxService>(); }
}
public void OnAKey() {
MessageBoxService.ShowMessage("Key Command: A");
}
public void OnAltAKey() {
MessageBoxService.ShowMessage("Key Command: Alt+A");
}
}
Use the following fluent API methods of the MvvmContext component to bind these commands to related keys:
WithKey | The first method parameter is a UI element that must be focused when end-users press certain keys. The second parameter is a key combination. |
KeyToCommand | Refers to a command that should be executed. |
The code below binds the “OnAKey” and “OnAltKey” commands to “A” and “Alt+A” keys respectively. Pressing both key combinations fires related commands only if the memo edit control currently has focus.
mvvmContext.ViewModelType = typeof(KeyAwareViewModel);
// Binding the "A" key
mvvmContext.OfType<KeyAwareViewModel>()
.WithKey(memo, Keys.A)
.KeyToCommand(x => x.OnAKey());
// Binding the "Alt+A" shortcut
mvvmContext.OfType<KeyAwareViewModel>()
.WithKey(memo, Keys.A | Keys.Alt)
.KeyToCommand(x => x.OnAltAKey());
Binding multiple keys to the same command
You want to bind multiple keys to the same command and pass these keys as parameters, use the WithKeys and KeysToCommands methods. Below is the sample KeyAwareViewModel View Model that contains parameterized “OnKey” and “OnKeyArgs” commands. These commands notify users what keys have been pressed.
public class KeyAwareViewModel {
protected IMessageBoxService MessageBoxService {
get { return this.GetService<IMessageBoxService>(); }
public void OnKey(Keys keys) {
MessageBoxService.ShowMessage("Key Command:" + keys.ToString());
}
public void OnKeyArgs(KeyEventArgs args) {
string message = string.Join(", ",
"KeyValue: " + args.KeyValue.ToString(),
"KeyData: " + args.KeyData.ToString(),
"KeyCode: " + args.KeyCode.ToString(),
"Modifiers: " + args.Modifiers.ToString());
MessageBoxService.ShowMessage("Args = {" + message + "}");
}
}
The code below binds these commands to multiple hotkeys at once.
mvvmContext.ViewModelType = typeof(KeyAwareViewModel);
// Binding to the OnKey command
mvvmContext.OfType<KeyAwareViewModel>()
.WithKeys(memo, new Keys[] { Keys.A, Keys.B, Keys.C })
.KeysToCommand(x => x.OnKey(Keys.None), args => args.KeyCode);
// Binding to the OnKeyArgs command
mvvmContext.OfType<KeyAwareViewModel>()
.WithKeys(memo, new Keys[] { Keys.Shift | Keys.A, Keys.Shift | Keys.B, Keys.Shift | Keys.C})
.KeysToCommand(x => x.OnKeyArgs((KeyEventArgs)null), args => (KeyEventArgs)args);
Custom Behaviors
You can implement a custom behavior if there is no ready DevExpress behavior for your needs. For instance, the Ctrl+C keyboard combination copies the entire GridView row by default. You can attach your own behavior if you need to copy the value of the selected row cell only.
public class ControlCBehavior : EventTriggerBase<System.Windows.Forms.KeyEventArgs> {
public ControlCBehavior()
: base("KeyDown") {
}
protected override void OnEvent() {
if (Args.Control && Args.KeyCode == System.Windows.Forms.Keys.C) {
var cbService = this.GetService<Services.IClipboardService>();
GridView View = Source as GridView;
if (View.GetRowCellValue(View.FocusedRowHandle, View.FocusedColumn) != null && View.GetRowCellValue(View.FocusedRowHandle, View.FocusedColumn).ToString() != String.Empty)
cbService.SetText(View.GetRowCellValue(View.FocusedRowHandle, View.FocusedColumn).ToString());
else
XtraMessageBox.Show("The value in the selected cell is null or empty!");
Args.Handled = true;
}
}
}
This behavior uses the custom IClipboardService service that copies text to a clipboard.
public class ClipboardService : IClipboardService {
public void SetText(string text) {
Clipboard.SetText(text);
}
}
public interface IClipboardService {
void SetText(string text);
}
After the custom behavior is ready, register the service and call the AttachBehavior method to attach the behavior to the grid view.
mvvmContext1.RegisterService(new Services.ClipboardService());
mvvmContext1.AttachBehavior<Behaviors.ControlCBehavior>(gridView1);
The custom behavior now suppresses the default shortcut handler and copies only the selected cell value.