Search code examples
c#wpfmvvmevent-handlingeventtrigger

Losing EventArgs after Routing of Attached Event WPF/MVVM


I am doing MVVM project and I have such problem: after Routing of some Attached Event, I'm losing EventArgs. For RoutingEvent I used this code:

public class RoutedEventTrigger : EventTriggerBase<DependencyObject>
    {
        RoutedEvent _routedEvent;

        public RoutedEvent RoutedEvent
        {
            get { return _routedEvent; }
            set { _routedEvent = value; }
        }

        public RoutedEventTrigger()
        {
        }
        protected override void OnAttached()
        {
            Behavior behavior = base.AssociatedObject as Behavior;
            FrameworkElement associatedElement = base.AssociatedObject as FrameworkElement;

            if (behavior != null)
            {
                associatedElement = ((IAttachedObject)behavior).AssociatedObject as FrameworkElement;
            }
            if (associatedElement == null)
            {
                throw new ArgumentException("Routed Event trigger can only be associated to framework elements");
            }
            if (RoutedEvent != null)
            {
                associatedElement.AddHandler(RoutedEvent, new RoutedEventHandler(this.OnRoutedEvent));
            }
        }
        void OnRoutedEvent(object sender, RoutedEventArgs args)
        {
            base.OnEvent(args);
        }
        protected override string GetEventName()
        {
            return RoutedEvent.Name;
        }
    }

Part from xaml:

<ListView>
  <i:Interaction.Triggers>
    <localP:RoutedEventTrigger RoutedEvent="ScrollViewer.ScrollChanged">
      <cmd:EventToCommand Command="{Binding ScrollCommand}" />
    </localP:RoutedEventTrigger>
  </i:Interaction.Triggers>

My handler in MVVM :

ScrollCommand = new RelayCommand<ScrollChangedEventArgs>(e =>
            {
                MessageBox.Show("HorizontalChange " + e.HorizontalChange");
            });

Handler is invoked, but e is null. What I'm doing wrong and how can i get that Args?

As mvvm base I using mvvm-light.


Solution

  • Hi you should set the PassEventArgsToCommand to true on the EventToCommand.