问题
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