Dynamically defined event handler using a DataTrigger

iv'e received several controls that I need to bind an event handler for their PreviewMouseLeftButtonDown event only when a certain condition is met.

iv'e designed a style for my controls using a datatrigger, I checked its bindings and tried it with a regular property setting tool for the BorderThickness property to see if the datatrigger works, (It does ..)

how can I apply my datatrigger to attach an event handler when the datatrigger condition is executed using the event setter in the same way, I would use a regular set of properties?

something like:

<Style TargetType="{x:Type ItemsControl}"> <Style.Triggers> <DataTrigger Binding="{Binding Turn}" Value="True"> <EventSetter Event="PreviewMouseLeftButtonDown" Handler="ItemsControl_MouseLeftButtonDown"></EventSetter> </DataTrigger> </Style.Triggers> </Style> 

this markup raises the following exception in the event set string:

  'Set property 'System.Windows.EventSetter.Event' threw an exception.' 

Internal exception:

  {"Value cannot be null.\r\nParameter name: value"} 
+7
source share
1 answer

Unfortunately, according to the MSDN document in the Notes section:

Note that only Style.Setters supports EventSetters . Triggers (TriggerBase and derived classes) not EventSetter support

In this case, the DataTrigger is derived from TriggerBase, so you cannot use it to dynamically control event handlers. A workaround I can think of right now might be to dynamically switch styles based on the Turn value.

+11
source

All Articles