Dynamically set event handler using DataTrigger

南楼画角 提交于 2020-01-14 07:42:05

问题


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"}

回答1:


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.



来源:https://stackoverflow.com/questions/9673966/dynamically-set-event-handler-using-datatrigger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!