How to pass ScrollChangedEventArgs as CommandParameter? RRS feed

  • Question

  • Hi,


    In Our application, we are using C# WPF with  MVVM pattern.


    For the ListBox control, we need to bind ICommand property to ScrollViewer.ScrollChanged event. As this is Routed event, it will not support binding by default.

    So we implemented custom routed event as below :


    Triggers inside ListBox control

    <ListBox x:Name="DirList" BorderBrush="Black" BorderThickness="1">


       <i_local:RoutedEventTrigger RoutedEvent ="ScrollViewer.ScrollChanged" SourceName="DirList" >

           <i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl }}, Path=DataContext.ScrollViewerScrollChangedCommand }" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox }}}" />







    public class RoutedEventTrigger : EventTriggerBase<DependencyObject>


            public RoutedEventTrigger()





            // Command

            public ICommand Command { get { return (ICommand)GetValue(CommandProperty); } set { SetValue(CommandProperty, value); } }

            public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(RoutedEventTrigger), new PropertyMetadata(null));



            private RoutedEvent routedEvent;

            public RoutedEvent RoutedEvent


                get { return routedEvent; }

                set { routedEvent = value; }



            protected override string GetEventName()


                return RoutedEvent.Name;



            void OnRoutedEvent(object sender, RoutedEventArgs args)





            protected override void OnAttached()


                Behavior behavior = base.AssociatedObject as Behavior;

                FrameworkElement frameworkElement = base.AssociatedObject as FrameworkElement;


                if (behavior != null)


                    frameworkElement = ((IAttachedObject)behavior).AssociatedObject as FrameworkElement;



                if (frameworkElement == null)


                    throw new ArgumentException("Routed Event trigger can only be associated to framework elements");



                if (RoutedEvent != null)


                    frameworkElement.AddHandler(RoutedEvent, new RoutedEventHandler(this.OnRoutedEvent));







    In above example we passed CommandParameteras ListBox and, in ScrollChanged event we are extracting scrollViewer from the listbox each time.

    It is working fine for us.


    In order to optimize code further:

    We were unable to pass ScrollChangedEventArgs as CommandParameter. Please suggest how we can pass ScrollChangedEventArgs as CommandParameter ?

    Thanks in Advance


    Wednesday, September 5, 2018 3:38 AM