Event.split<'T,'U1,'U2,'Del> 函数 (F#)

更新:2010 年 9 月

返回一个新事件,该事件会侦听原始事件,如果将函数应用于事件参数时返回 Choice1Of2,则触发第一个结果事件;如果返回 Choice2Of2,则触发第二个事件。

命名空间/模块路径: Microsoft.FSharp.Control.Event

程序集:FSharp.Core(在 FSharp.Core.dll 中)

// Signature:
Event.split : ('T -> Choice<'U1,'U2>) -> IEvent<'Del,'T> -> IEvent<'U1> * IEvent<'U2> (requires delegate)

// Usage:
Event.split splitter sourceEvent

参数

  • splitter
    类型:'T -> Choice<'U1,'U2>

    一个函数,它通常是一个活动模式识别器,可将事件值转换为两种类型之一。

  • sourceEvent
    类型:IEvent<'Del,'T>

    输入事件。

返回值

事件的元组。 只要 splitter 的计算结果为 Choice1of1,就会激发第一个;只要 splitter 的计算结果为 Choice2of2,就会激发第二个。

备注

此函数在编译的程序集中名为 Split。 如果从 F# 以外的语言中访问函数,或通过反射访问成员,请使用此名称。

示例

以下代码演示如何使用 Event.split 函数来实现窗体上移动控件的能力 splitter 函数是主动模式识别器 (|Down|Up|),表明鼠标按钮的状态。 如果用户在鼠标移动到按钮上方时按下鼠标键,则按钮移动。 还存在不时更改移动中的按钮颜色的代码,具体取决于使用的鼠标按钮类型。 此测试对各鼠标按钮使用不同的颜色。 用于未按下鼠标按钮时的其他事件路径,将释放按钮之后恢复按钮的原始颜色。

open System.Windows.Forms
open System.Drawing
open Microsoft.FSharp.Core

let form = new Form(Text = "F# Windows Form",
                    Visible = true,
                    TopMost = true)

let button = new Button(Text = "Button",
                        Visible = true,
                        Left = 100,
                        Width = 50,
                        Top = 100,
                        Height = 20)

form.Controls.Add(button)
let originalColor = button.BackColor
let mutable xOff, yOff = (0, 0)

let (|Down|Up|) (evArgs:MouseEventArgs) =
    match evArgs.Button with
    | MouseButtons.Left 
    | MouseButtons.Right 
    | MouseButtons.Middle -> Down(evArgs)
    | _ -> Up

button.MouseDown 
|> Event.add(fun evArgs ->
    xOff <- evArgs.X
    yOff <- evArgs.Y)

form.MouseMove
|> Event.map (fun evArgs -> (evArgs.X, evArgs.Y))
|> Event.add (fun (x, y) -> form.Text <- sprintf "(%d, %d)" x y)

let (dragButton, noDragButton) = Event.split (|Down|Up|) button.MouseMove

// Move the button, and change its color if the user uses the
// right or middle mouse button.
dragButton |> Event.add ( fun evArgs ->
    match evArgs.Button with
    | MouseButtons.Left ->
        button.BackColor <- originalColor
    | MouseButtons.Right ->
        button.BackColor <- Color.Red
    | MouseButtons.Middle ->
        button.BackColor <- Color.Blue
    | _ -> ()
    button.Left <- button.Left + evArgs.X - xOff
    button.Top <- button.Top + evArgs.Y - yOff
    button.Refresh())

// Restore the button's original color when the mouse is moved after
// the release of the button.
noDragButton |> Event.add ( fun () -> 
    button.BackColor <- originalColor)

平台

Windows 7、Windows Vista SP2、Windows XP SP3、Windows XP x64 SP2、Windows Server 2008 R2、Windows Server 2008 SP2、Windows Server 2003 SP2

版本信息

F# 运行时

受以下版本支持:2.0、4.0

Silverlight

受以下版本支持:3

请参见

参考

Control.Event 模块 (F#)

Microsoft.FSharp.Control 命名空间 (F#)

修订记录

Date

修订记录

原因

2010 年 9 月

添加了代码示例。

信息补充。