New to Telerik UI for WPF? Download free 30-day trial

Use the Telerik EventToCommandBehavior in Style Setter

Environment

Product Telerik UI for WPF
Version 2022.3.1109

Description

How to add EventToCommandBehavior's EventBinding objects in a WPF Style Setter.

Solution

The EventToCommandBehavior.EventBindings attached collection property cannot be assigned, so EventBindings cannot be added in a Style Setter element. To do this, you can implement an attached property that adds EventBinding objects in the C# code.

Implementing the attached property.

    public static class EventToCommandBehaviorUtilities
    {
        public static EventBindingCollection GetEventBindings(DependencyObject obj)
        {
            return (EventBindingCollection)obj.GetValue(EventBindingsProperty);
        }

        public static void SetEventBindings(DependencyObject obj, EventBindingCollection value)
        {
            obj.SetValue(EventBindingsProperty, value);
        }

        public static readonly DependencyProperty EventBindingsProperty =
            DependencyProperty.RegisterAttached("EventBindings", typeof(EventBindingCollection), typeof(EventToCommandBehaviorUtilities), new PropertyMetadata(null, OnEventBindingsChanged));

        private static void OnEventBindingsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var eventBindingsCollection = EventToCommandBehavior.GetEventBindings(d);
            if (e.OldValue != null)
            {
                foreach (EventBinding item in (EventBindingCollection)e.OldValue)
                {
                    eventBindingsCollection.Remove(item);
                }
            }

            if (e.NewValue != null)
            {
                foreach (EventBinding item in (EventBindingCollection)e.NewValue)
                {
                    eventBindingsCollection.Add(item);
                }
            }
        }
    }

Using the attached property.

    <Style TargetType="Border">
         <Setter Property="local:EventToCommandBehaviorUtilities.EventBindings">
             <Setter.Value>
                 <telerik:EventBindingCollection>
                     <telerik:EventBinding EventName="MouseLeftButtonDown" Command="{Binding MyMouseLeftButtonDownCommand}" />
                     <telerik:EventBinding EventName="MouseMove" Command="{Binding MyMouseMoveCommand}" />
                 </telerik:EventBindingCollection>
             </Setter.Value>
         </Setter>
    </Style>
In this article