Binding UI Events from View to commands in ViewModel in Silverlight 4(转)

原文地址 :
http://blog.roboblob.com/2010/01/26/binding-ui-events-from-view-to-commands-in-viewmodel-in-silverlight-4/


Today we will touch another problem that people starting with MVVM very often fail to address properly:

Handling the UI Events of the View in the ViewModel while avoiding placing any logic in code behind of the View.

So our design goals for this post are:

  • We want to be able to wire-up UI Events to the commands in ViewModel via DataBinding in Xaml without any code behind in the View
  • View should not be aware of the ViewModel’s type or any other details of its existence – View should just use Silverlight’s DataBinding to access its ViewModel public properties (its DataContext) regardless of what is actually set to be there
  • We want to be able to handle any event that occurs in View (that includes not only Button clicks but also Mouse events,  Drag and Drop events, Loaded events etc).

When i was trying to solve this problem, i made a mistake.

I coupled the View with ViewModel,  made the View aware of the ViewModel via interface of the ViewModel.

View held the instance of ViewModel in its DataContext.

And then when some event fires in the View i would call a ViewModel method in code behind of the View (accessing it via local variable holding the ViewModel instance casted to interface that ViewModel is implementing).

While this approach works for all events in the View because you can create event handler for any View event, it has many drawbacks.

Main problems are:

  • View has to know about the ViewModel and it has to have a instance of the ViewModel injected somehow
  • we have to create event handlers in the View code behind .cs file for each event (this can be really boring, and im lazy to do repetitive code so that was really hard for me).

I didn’t like this solution at all and I immediately abandoned it.

Then i tried searching for possible solutions on the web and found the magical Expression Blend Samples.

Microsoft introduced Behaviors in Silverlight 3 with Blend 3 to help UI designers to have a flexible new way to add interactivity to applications.

Behaviors allow interactivity to be added to elements directly on the design surface in XAML without having to write additional code.

I will not go into details on Behaviors since there are tons of resources on the web on the subject,  you can read the original Blend 3 Behaviors announcement to get more info.

The great thing about Behaviors is that they introduced Triggers and very handy  EventTrigger and TriggerAction classes that are perfect match for our MVVM events scenario.

As you can read on the MSDN link EventTrigger  ‘Represents a trigger that applies a set of actions … in response to an event’.

So we can create a EventTrigger for some UI event in our View that will fire a custom TriggerAction that will call a method on our ViewModel with some parameters.

On the mentioned Expression Blend Samples page there is already implemented basic class for this – its called InvokeDataCommand and we will just customize it and extend (generalize it) so it serves our needs.

In the end we want to accomplish something like this in our View’s Xaml:

1<Interactivity:Interaction.Triggers>
2    <Interactivity:EventTrigger EventName="MouseMove">
3        <TriggerActions:MapMouseEventToCommand Command="{Binding Path=ShowMousePositionCommand}" />
4    </Interactivity:EventTrigger>
5</Interactivity:Interaction.Triggers>

So this is instructing our View to call the command called ShowMousePositionCommand on its ViewModel when mouse pointer is moved over some control.

So lets get started!

First we need to create a command class that we will be able to call from our Events.

Silverlight has only partial support for commanding.

Until Silverlight 4 ICommand interface was available – but without any real support or use.
In Silverlight 4 this interface is supported by Button type controls in again partial way:  in ButtonBase class from which all button-like controls inherit, there are two properties: Command and CommandParameter that you can point to a command that implements ICommand interface and pass it some parameter.

This can be done via DataBinding and when you click the button this command will be executed with the specified parameter. No code solution, pure XAML!
The problem is that Silverlight 4 Beta does not offer any implementation of the ICommand interface so we have to do this by ourselves.

Here is the ICommand interface:

1namespace System.Windows.Input
2{
3    public interface ICommand
4    {
5        bool CanExecute(object parameter);
6        void Execute(object parameter);
7        abstract event EventHandler CanExecuteChanged;
8    }
9}

So it basically defines a contract: Any command that will implement this interface we we will be able to query it if we can ececute it (CanExecute) and execute it with parameter via its Execute method,  also there is an event CanExecuteChanged so that anyone can subscribe to it in order to be notified if CanExecute status of command has changed (this is used by UI controls so that buttons become disabled if command is disabled etc).

But before we implement this lets make a slight modification and create another interface IDelegateCommand that will implement ICommand interface and just add one method RaiseCanExecuteChanged();

This new method is there so that we can invoke it from code if we know that status of our command has changed – so by invoking it we can notify the UI of this change.

So here is the new IDelegateCommand interface:

1public interface IDelegateCommand : ICommand
2{
3    void RaiseCanExecuteChanged();
4}

And here is our generic version of DelegateCommand class that implements IDelegateCommand and ICommand:

01public class DelegateCommand<T> : IDelegateCommand
02{
03  private readonly Action<T> executeAction;
04  private readonly Func<T, bool> canExecuteAction;
05 
06  public DelegateCommand(Action<T> executeAction, Func<T, bool> canExecuteAction)
07  {
08    this.executeAction = executeAction;
09    this.canExecuteAction = canExecuteAction;
10  }
11 
12  public DelegateCommand(Action<T> executeAction) : this(executeAction, null)
13  {
14  }
15 
16  /// <summary>
17  /// Defines the method that determines whether the command can execute in its current state.
18  /// </summary>
19  /// <returns>
20  /// true if this command can be executed; otherwise, false.
21  /// </returns>
22  /// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null. </param>
23  public bool CanExecute(object parameter)
24  {
25    if (canExecuteAction != null)
26    {
27      return canExecuteAction((T) parameter);
28    }
29    return true;
30  }
31 
32  /// <summary>
33  /// Defines the method to be called when the command is invoked.
34  /// </summary>
35  /// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null. </param>
36  public void Execute(object parameter)
37  {
38    if (CanExecute(parameter))
39    {
40      executeAction((T) parameter);
41    }
42  }
43 
44  protected void OnCanExecuteChanged(object sender, EventArgs args)
45  {
46      var handler = this.CanExecuteChanged;
47      if (handler != null)
48      {
49          handler(sender, args);
50      }
51  }
52 
53  public void RaiseCanExecuteChanged()
54  {
55      this.OnCanExecuteChanged(this, EventArgs.Empty);
56  }
57 
58  public event EventHandler CanExecuteChanged;
59}

Its simple generic class that allows us to create commands on our ViewModels that will be triggered when needed.

I wont go into much details of this class since there are a lot of posts on this on the web. Be sure to check out Prism DelegateCommand version since my implementation is mostly based on their code.

Now that we have a way of specifying the commands that we will trigger let’s see how we will trigger them.

Back to our Behaviors:  We will create base generic class that will inherit from TriggerAction<FrameworkElement> and we will use this class to build specific TriggerActions for different UI events:

01public abstract class MapEventToCommandBase<TEventArgsType> : TriggerAction<FrameworkElement>
02    where TEventArgsType : EventArgs
03{
04    public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(IDelegateCommand), typeof(MapEventToCommandBase<TEventArgsType>), new PropertyMetadata(null, OnCommandPropertyChanged));
05    public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof(object), typeof(MapEventToCommandBase<TEventArgsType>), new PropertyMetadata(null, OnCommandParameterPropertyChanged));
06 
07    private static void OnCommandParameterPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
08    {
09        var invokeCommand = d as MapEventToCommand;
10        if (invokeCommand != null)
11        {
12            invokeCommand.SetValue(CommandParameterProperty, e.NewValue);
13        }
14    }
15 
16    private static void OnCommandPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
17    {
18        var invokeCommand = d as MapEventToCommand;
19        if (invokeCommand != null)
20        {
21            invokeCommand.SetValue(CommandProperty, e.NewValue);
22        }
23    }
24 
25    protected override void Invoke(object parameter)
26    {
27        if (this.Command == null)
28        {
29            return;
30        }
31 
32        if (this.Command.CanExecute(parameter))
33        {
34            var eventInfo = new EventInformation<TEventArgsType>
35                                {
36                                    EventArgs = parameter as TEventArgsType,
37                                    Sender = this.AssociatedObject,
38                                    CommandArgument = GetValue(CommandParameterProperty)
39                                };
40            this.Command.Execute(eventInfo);
41        }
42    }
43 
44    public IDelegateCommand Command
45    {
46        get
47        {
48            return (IDelegateCommand)base.GetValue(CommandProperty);
49        }
50        set
51        {
52            base.SetValue(CommandProperty, value);
53        }
54    }
55 
56    public object CommandParameter
57    {
58        get
59        {
60            return base.GetValue(CommandParameterProperty);
61        }
62        set
63        {
64            base.SetValue(CommandParameterProperty, value);
65        }
66    }
67}

Our MapEventToCommandBase class simply adds Command and CommandParameter DependencyProperties so we can set via DataBinding the command and (optionally) parameter for the event.
It has one type parameter TEventArgsType that it uses so it can send the appropriate EventArgs from the Event that occurred to the command we are calling.
That is why TEventArgsType has a constraint that it has to inherit from EventArgs since every UI event sends some information in a class that inherits from EventArgs or sends EventArgs.Empty.

The meat of this class is the method Invoke that overrides the method in its base class TriggerAction.
This method is called from the Silverlight runtime when some event occurs in the UI and the parameter sent is the instance of class that inherits from EventArgs and carries the information specific to that event (MouseEventArgs, DragEventArgs, KeybardEventArgs etc).

What we do in this method is that we take that event information we received and pack it into new class that we will send to our command.

Its this part of code:

01if (this.Command.CanExecute(parameter))
02{
03    var eventInfo = new EventInformation<TEventArgsType>
04                        {
05                            EventArgs = parameter as TEventArgsType,
06                            Sender = this.AssociatedObject,
07                            CommandArgument = GetValue(CommandParameterProperty)
08                        };
09    this.Command.Execute(eventInfo);
10}

So we construct the instance of generic EventInformation class of certain EventArgs inheritor type and we include there the sender of the event and the optional argument we sent from XAML binding.

Here is how the generic EventInformation class looks like:

1public class EventInformation<TEventArgsType> where TEventArgsType : EventArgs
2{
3    public object Sender { get; set; }
4    public TEventArgsType EventArgs { get; set; }
5    public object CommandArgument { get; set; }
6}

It allows us to easily create strongly typed class for each of possible events that can occur in the UI.
For RoutedEvents like Loaded event the RoutedEventArgs will be passed there.

Lets continue. Since our MapEventToCommandBase is abstract and generic class we need to inherit it to be able to actually use it in Xaml so here are some examples of concrete MapSOMEKINDOFEventToCommand implementations:

First MapMouseEventToCommand:

1public class MapMouseEventToCommand : MapEventToCommandBase<MouseEventArgs>
2{
3 
4}

So as you see there is nothing we need to implement here, just to specify the type of the event we want to handle.
If Xaml would support generics we could make the MapEventToCommandBase not to be abstract and use it directly but until Xaml learns to accept generics this is the best way i could figure out.

Then there is the MapKeyboardEventToCommand:

1public class MapKeyboardEventToCommand : MapEventToCommandBase<KeyEventArgs>
2{
3 
4}

So we can do this for any type of event that we need (see the sample Visual Studio 2010 Project for more examples)

If we don’t need the specific EventArgs we can also use the MapEventToCommand class that uses EventArgs as its type so it can be used with ANY event.
The drawback is that in the command we will receive the EventInformation<EventArgs> so we need to cast the EventArgs property of that class to some specific EventArgs inheritor class so we lose type safety.

So now that all is in place lets see how we can use our new magic classes from Xaml in Views.

First the simplest event: Loaded.

In Xaml of our View we must place this code:

1<Interactivity:Interaction.Triggers>
2    <Interactivity:EventTrigger EventName="Loaded">
3        <TriggerActions:MapEventToCommand Command="{Binding Path=LoadedCommand}" CommandParameter="Shell view loaded at {0:d/M/yyyy HH:mm:ss:fff tt}" />
4    </Interactivity:EventTrigger>
5</Interactivity:Interaction.Triggers>

So we are creating EventTrigger for event with name “Loaded” and for this event we are setting TriggerAction to our MapEventToCommand. This event will trigger when control is loaded and since we use DataBinding to set the Command property, when the event occurs, LoadedCommand on our DataContext will be invoked with the string parameter we hard coded in CommandParameter (we could used DataBinding there also but i skipped this for now to keep things simple).

Next, in our ViewModel we have to define the actual LoadedCommand command.

Important note: DO NOT FORGET to always use OnPropertyChanged in the command’s property setter if you want all of this to work properly:

01private ICommand loadedCommand;
02public ICommand LoadedCommand
03{
04    get { return loadedCommand; }
05    private set
06    {
07        loadedCommand = value;
08        this.OnPropertyChanged("LoadedCommand");
09    }
10}

Another note: we are defining our command as ICommand property and later we will set them with DelegateCommands instances but this is off course perfectly fine since DelegateCommand implements IDelegateCommand that implements ICommand interface.

And in the constructor of ViewModel with single lambda we added the actual code that will run when command is executed (we just set some string property called LoadedTime to the current DateTime formated by the format text given in the parameter).

Since the View is bound to this LoadedTime property it’s shown on the control when its changed, triggered by INotifyPropertyChanged:

1this.LoadedCommand
2    = new DelegateCommand<EventInformation<EventArgs>>
3        (p =>
4             {
5                 LoadedTime = string.Format(p.CommandArgument.ToString(), DateTime.Now);
6             });

Lets see how we would map a MouseMove event:

1<Interactivity:Interaction.Triggers>
2 
3    <Interactivity:EventTrigger EventName="MouseMove">
4        <TriggerActions:MapMouseEventToCommand Command="{Binding Path=ShowMousePositionCommand}" />
5    </Interactivity:EventTrigger>
6 
7</Interactivity:Interaction.Triggers>

So we are doing the same thing here only we are using MapMouseEventToCommand in stead of the basic MapEventToCommand – we are doing this so we get strongly typed MouseEventArgs from the original event passed as EventArgs parameter in the EventInformation class that will be passed to the command.

Here is the command definition from our ViewModel:

1private ICommand showMousePositionCommand;
2public ICommand ShowMousePositionCommand
3{
4    get { return showMousePositionCommand; }
5    set { showMousePositionCommand = value;
6    this.OnPropertyChanged("ShowMousePositionCommand");
7 
8    }
9}

And here is part of the ViewModel constructor where we actually define the code triggered inside the command:

1this.ShowMousePositionCommand
2    = new DelegateCommand<EventInformation<MouseEventArgs>>(
3    p =>
4    {
5        this.MousePosition = string.Format("x:{0} y:{1}",
6            p.EventArgs.GetPosition(null).X, p.EventArgs.GetPosition(null).Y);
7    });

What happens here is that when our command is invoked (this is triggered when user moves his mouse pointer in our View) we use the received MouseEventArgs (from EventArgs property) of the EventInformation instance to get the current mouse position and we create a string representation of it and we set a public property on our ViewModel.

And our View is again data-bound to this property – so it will get notification that its value has changed and re-display it on screen so we will have realtime coordinates of our mouse pointer displayed in the view as we move the pointer.

Check out the demo application to see this in action.

So we managed to wire up events from View to the ViewModel in Xaml via DataBinding.

Here is how our View’s backend code .cs file looks like:

01using System.Windows.Controls;
02 
03namespace EventCommands.Views
04{
05    public partial class ShellView : UserControl
06    {
07        public ShellView()
08        {
09            InitializeComponent();
10        }
11    }
12}

As you can see we added zero logic to our View – its only code generated by the Visual Studio when we created the UserControl for the, so its clean design, decoupled View from the ViewModel, and we can later change our Views and our ViewModels won’t event notice ;)

For those that do not have Silverlight 4 installed yet, here is the screen shot of the running demo application showing all the code we have written for this experiment:

If you run the application you will see two independent instances of the small sample EventsWidget for showing Events triggered on View.

Currently im demonstrating MouseMove event, DragAndDrop event, KeyDown event and also Loaded event.

Other UI events can be easily added and are completely supported by the given code.

I deliberately added two instances of same widget on the main page so its clear that data binding works independently and that each control can has its own ViewModel and DataBinds events to Commands in its own ViewModel.

In same way the main control (ShellView) has its own ViewModel and its own Events DataBound to commands in its own ViewModel etc.

 

posted @ 2011-07-01 16:31    阅读(404)  评论(0编辑  收藏  举报