Home > WPF > How to attached an MVVM EventToCommand to an Attached event

How to attached an MVVM EventToCommand to an Attached event

In my daily lif e of developer, I am using every time the MVVM Light tool kit which offer me flexibility and set up of the model in an easy and efficient way. On a recent Microsoft PIxelSense project I get the need to bind my MVVM to an attached event. So at first I thought it should be similar as a normal event so I start to setup my triggers as follow:

<s:SurfaceSlider Name=”timelineSlider” Grid.Row=”1″ >
<i:Interaction.Triggers>
  
<helpers:RoutedEventTrigger RoutedEvent=”Thumb.DragStarted” >
    
<cmd:EventToCommand Command=”{Binding Mode=OneWay, Path=SeekStartedCmd}” PassEventArgsToCommand=”True” />
</helpers:RoutedEventTriggers>

The code above, is based on a player way I need to use a slider for a Seek method. So to track the change on the slider, one of the events I need to catch was the one from the Thumb.

At first look it sounds promising, no error, and code run perfectly but the event get not catch.

 We can’t invoke command on attached events. For example we can’t invoke command on Thumb.DragStarted

 How to handle attached event:

After some research on the web and shaking different type of information I came across the following class which will help to solve my issue. We create a new trigger which fires on attached event by inheriting EventTriggerBase<T> class.

namespace Solatys.Helpers
{

 publicclassRoutedEventTrigger : EventTriggerBase<DependencyObject>
    {
        RoutedEvent _routedEvent;
        publicRoutedEvent RoutedEvent
        {
            get
            {
                return _routedEvent;
            }
            set { _routedEvent = value; }
        }

        public RoutedEventTrigger() { }
        protected override void OnAttached()
        {
            Behavior behavior = base.AssociatedObject asBehavior;
            FrameworkElement associatedElement = base.AssociatedObject asFrameworkElement; if (behavior != null)
            {
                associatedElement = ((IAttachedObject)behavior).AssociatedObject asFrameworkElement;
            } if (associatedElement == null)
            {
                thrownewArgumentException(“Routed Event trigger can only be associated to framework elements”);
            }
            if (RoutedEvent != null)
            {
                associatedElement.AddHandler(RoutedEvent, newRoutedEventHandler(this.OnRoutedEvent));
            }
        }

        void OnRoutedEvent(object sender, RoutedEventArgs args)
        {
            base.OnEvent(args);
        }

        protected override string GetEventName()
        {
            return RoutedEvent.Name;
        }
    }
}

 How to use it :

<s:SurfaceSlider Name=”timelineSlider” Grid.Row=”1″>
 
<i:Interaction.Triggers>
   <helpers:RoutedEventTrigger RoutedEvent=”Thumb.DragStarted” >
    <cmd:EventToCommand Command=”{Binding Mode=OneWay, Path=SeekStartedCmd}”
      PassEventArgsToCommand
=”True” />
  </i:Interaction.Triggers>
</s:SurfaceSlider>

 Happy coding

Advertisements
Categories: WPF Tags:
  1. thunder
    October 22, 2012 at 10:16 pm

    I was wondering how i could solve my problem, and you give me the solution with that post. I appreciate your sample. I have implement it and works like a charm. Thks serge, great job for your blog in general too

  2. July 1, 2013 at 9:53 am

    I tried to use it on a TextBox Validation.Error – it returns an error:
    RoutedEventConverter cannot convert from System.String.
    I would love to get help.

    • Serge
      July 1, 2013 at 9:59 am

      This as not been plan for use with error validation but instead connect an MVVM pattern to a routed event like in the sample

  3. Arne Deruwe
    July 11, 2013 at 2:29 pm

    Hodaya got his answer here: http://stackoverflow.com/questions/17401082/eventtocommand-with-attached-event
    I can confirm this works 🙂

    • Serge
      July 11, 2013 at 2:34 pm

      great 🙂

  4. November 6, 2013 at 6:11 am

    thanks, solution work just perfect 🙂
    kudos to you.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: