使用 XAML 标记的 F# 事件处理程序
F# Event Handler using XAML markup
既然我有一个 ,我如何在 XAML 中指定一个处理程序?
<Window.Resources>
<Style TargetType="Grid">
<Setter Property="funk:Tap.Handler"
Value="{Binding TapHandler}"/>
</Style>
</Window.Resources>
允许:
- 用于处理冒泡或隧道 RoutedEvents 的 UIElements,而不仅仅是引发它们的控件
- 使用隐式样式,无需为特定类型的每个 UIElement 连接事件
- 根据 ViewModel 中的逻辑更改处理程序
- 没有代码隐藏的视图
使用附加的 属性(基于 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 演示文件here (FsXaml 2.1.0)
既然我有一个
<Window.Resources>
<Style TargetType="Grid">
<Setter Property="funk:Tap.Handler"
Value="{Binding TapHandler}"/>
</Style>
</Window.Resources>
允许:
- 用于处理冒泡或隧道 RoutedEvents 的 UIElements,而不仅仅是引发它们的控件
- 使用隐式样式,无需为特定类型的每个 UIElement 连接事件
- 根据 ViewModel 中的逻辑更改处理程序
- 没有代码隐藏的视图
使用附加的 属性(基于 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 演示文件here (FsXaml 2.1.0)