New to Telerik UI for WPFStart a free 30-day trial

Use the Telerik EventToCommandBehavior in Style Setter

Updated over 6 months ago

Environment

ProductTelerik UI for WPF
Version2022.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.

csharp
	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.

xaml
	<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
EnvironmentDescriptionSolution
Not finding the help you need?
Contact Support