有谁知道如何将 F# 事件处理程序添加到 xaml 文件中的控件?
最佳答案
我刚刚在 F# 中(在伦敦)进行了一次关于使用 Silverlight 实现大多数示例的响应式(Reactive)编程的演讲。演讲已被录制,样本也可供下载,因此这可能是一个有用的资源:
要回答您的具体问题,我认为您不能使用在 XAML 文件中指定事件处理程序的常用样式(这可能适用于 F# Silverlight 应用程序,但您必须使用
member
而不是 let
函数)。但是,编写 Silverlight 组件的最佳方式(我能想到的)是只拥有一个 F# Silverlight 库并从 C# Silverlight 应用程序中使用它。在这种情况下,您需要在代码中编写事件处理程序绑定(bind)。一个简化的示例(来自演讲中的一个示例)如下所示:
open System.Windows.Controls
// Dynamic invoke operator that makes accessing XAML elements easy
// (easier than using 'FindName' explicitly in the code
let (?) (this : Control) (prop : string) : 'T = // '
this.FindName(prop) :?> 'T // '
type MyControl() as this =
inherit UserControl()
do
let path = "/MyProject;component/MyControl.xaml"
let uri = new System.Uri(path, UriKind.Relative)
Application.LoadComponent(this, uri)
// Get Button named 'TestButton' from the XAML file
let btn : Button = this?TestButton
// Add event handler to the button
btn.Add(fun _ -> btn.Text <- "Clicked!")
关于silverlight - 在 xaml 中添加 f# 函数作为事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3135952/