F#/WPF 事件绑定 [英] F#/WPF event binding

查看:25
本文介绍了F#/WPF 事件绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法将 XAML 中定义的事件挂接到成员的 F# 函数?当然,我可以用图表来做,但这有点不方便.

I am wandering if there is a way of hooking an event defined in XAML to a F# function of member ? Of course, I could do it diagrammatically but it is kind of inconvenient.

推荐答案

我想问题是您是否可以使用 XAML 标记将 F# 成员指定为事件处理程序:

I suppose the question is whether you can specify F# member as an event handler using XAML markup:

<Button x:Name="btnClick" Content="Click!" Click="button1_Click" />

据我所知,答案是.

这在 C# 中的工作方式是,事件处理程序的注册是在设计器生成的 C# 代码(部分类)中完成的(您可以在 obj 目录中名为例如 <代码>MainForm.g.cs).F# 没有对 WPF 设计器的任何直接支持,因此它无法为您生成它.您必须编写代码来手动附加事件处理程序(但这很容易).

The way this works in C# is that the registration of event handler is done in C# code (partial class) generated by the designer (you can see that in the obj directory in files named e.g. MainForm.g.cs). F# doesn't have any direct support for WPF designer, so it cannot generate this for you. You'll have to write the code to attach event handlers by hand (but that's quite easy).

我在我的伦敦谈论 Silverlight 中有一些例子.您可以实现 ? 运算符来很好地访问 XAML 元素:

I have some examples in my London talk about Silverlight. You can implement the ? operator to get nice access to the XAML elements:

 type MainPage() as this =
   inherit UserControl()
   let uri = new System.Uri("/App;component/MainPage.xaml", UriKind.Relative)
   do Application.LoadComponent(this, uri)

   // Get button using dynamic access and register handler
   let btn : Button = this?btnClick
   do btnClick.Click.Add(fun _ -> (* ... *))

我使用的 ? 运算符声明是:

The ? operator declaration that I used is:

let (?) (this : Control) (prop : string) : 'T = // '
  this.FindName(prop) :?> 'T

这篇关于F#/WPF 事件绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆