Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically set event handler using DataTrigger

iv'e got several itemscontrols which i need to attach an event handler for their PreviewMouseLeftButtonDown event only when a certain condition is met .

iv'e designed a style for my controls with a datatrigger ,i checked out it's bindings and tried it out with a regular property setter for the BorderThickness Property just to see that the datatrigger works . (It does..)

how can i apply my datatrigger to attach an event handler when the condition of the datatrigger is met using an event setter in the same manner i would a regular property setter ?

something along the lines of :

     <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 throws the following exception on the eventsetter line :

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

Inner Exception :

       {"Value cannot be null.\r\nParameter name: value"}
like image 430
eran otzap Avatar asked Mar 12 '12 20:03

eran otzap


1 Answers

Unfortunately according to MSDN doc under Remarks:

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

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

like image 131
XiaoChuan Yu Avatar answered Oct 21 '22 14:10

XiaoChuan Yu