Skip to content

Latest commit

 

History

History
89 lines (74 loc) · 2.72 KB

kb-common-eventtocommandbehavior-style-setter.md

File metadata and controls

89 lines (74 loc) · 2.72 KB
title description type page_title slug tags res_type ticketid
Use the Telerik EventToCommandBehavior in Style Setter
How to add EventBinding objects to EventToCommandBehavior in a WPF Style Setter.
how-to
Adding Event to Command Behavior's EventBindings for a Control in Style Setter
kb-common-eventtocommandbehavior-style-setter
radchartview, wpf, mvvm, cartesiangridlineannotation, mouseevents
kb
1674339

Environment

Product Telerik UI for WPF
Version 2022.3.1109

Description

How to add [EventToCommandBehavior's]({%slug common-event-to-command-behavior%}) 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>