F# Event Handler using XAML markup

两盒软妹~` 提交于 2019-12-23 23:40:50

问题


Now that I have a Custom Routed Event, how can I specify a handler in XAML?

<Window.Resources>
    <Style TargetType="Grid">
        <Setter Property="funk:Tap.Handler"
                Value="{Binding TapHandler}"/>
    </Style>
</Window.Resources>

Allowing:

  • UIElements to handle bubbling or tunneling RoutedEvents, not just the Controls raising them
  • The use of implicit Styles, eliminating the need to wire the event for each UIElement of a certain Type
  • Change of handler based on logic in ViewModel
  • a View with no code-behind

回答1:


Using an Attached Property (based on this post)

type Tap() =
    inherit DependencyObject()

    // For easy exchange
    static let routedEvent = MyButtonSimple.TapEvent

    static let HandlerProperty =
        DependencyProperty.RegisterAttached
            ( "Handler", typeof<RoutedEventHandler>, 
                typeof<Tap>, new PropertyMetadata(null))

    static let OnEvent (sender : obj) args = 
        let control = sender :?> UIElement
        let handler = control.GetValue(HandlerProperty) :?> RoutedEventHandler
        if not <| ((handler, null) ||> LanguagePrimitives.PhysicalEquality) then
            handler.Invoke(sender, args)

    static do EventManager.RegisterClassHandler(
                typeof<FrameworkElement>, routedEvent, 
                    RoutedEventHandler(OnEvent))

    static member GetHandler (element: UIElement) : RoutedEventHandler = 
        element.GetValue(HandlerProperty) :?> _

    static member SetHandler (element: UIElement, value : RoutedEventHandler) = 
        element.SetValue(HandlerProperty, value)

wpfApp demo files can be found here (FsXaml 2.1.0)



来源:https://stackoverflow.com/questions/39350220/f-event-handler-using-xaml-markup

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