我该如何在F#中使用WPF菜单和对话框?

4

我一直在尝试寻找一个使用XAML和F#(不使用C#)来设置传统菜单和对话框的示例。我在网上找到的所有内容要么使用C#,要么是旧版本的F#和.NET。有没有人能推荐一个我可以参考的示例?谢谢。


3
http://fsprojects.github.io/FsXaml/ - CaringDev
2
你需要使用FsXAML和FSharp.ViewModule或Gjallarhorn来进行绑定。后者有一些示例。 - s952163
谢谢你们两个的回复。我会去你们建议的地方看看并尝试弄清楚。如果还有其他人有任何想法,请添加到这个列表中。 - Bob McCrory
2
由于这是相当开放的,您可能应该访问F#聊天室,甚至更好的是F# Slack - s952163
我想使用聊天室,但是我是新来的,只有19个声望点,需要20个才能发帖。 - Bob McCrory
1个回答

3
当您尝试学习WPF时,可能会遇到许多基于“老旧”的代码后台而不是MVVM或MVC的C#示例。以下内容解释了如何快速创建一个F# WPF代码后台应用程序,使用它可以更轻松地尝试所有这些示例。
创建一个F#控制台应用程序。
更改应用程序的“输出类型”为“Windows应用程序”。
从NuGet添加FsXaml。
添加这四个源文件,并按照以下顺序排列。
MainWindow.xaml
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="First Demo" Height="200" Width="300">
    <Canvas>
        <Button Name="btnTest" Content="Test" Canvas.Left="10" Canvas.Top="10" Height="28" Width="72"/>
    </Canvas>
</Window>

MainWindow.xaml.fs

namespace FirstDemo

type MainWindowXaml = FsXaml.XAML<"MainWindow.xaml">

type MainWindow() =
    inherit MainWindowXaml()

    let whenLoaded _ =
        ()

    let whenClosing _ =
        ()

    let whenClosed _ =
        ()

    let btnTestClick _ =
        this.Title <- "Yup, it works!"
        ()

    do
        this.Loaded.Add whenLoaded
        this.Closing.Add whenClosing
        this.Closed.Add whenClosed
        this.btnTest.Click.Add btnTestClick

App.xaml

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Application.Resources>
    </Application.Resources>
</Application>

App.xaml.fs

namespace FirstDemo

open System
open System.Windows

type App = FsXaml.XAML<"App.xaml">

module Main =

    [<STAThread; EntryPoint>]
    let main _ =
        let app = App()
        let mainWindow = new MainWindow()
        app.Run(mainWindow) // Returns application's exit code.

删除Program.fs文件。

将两个xaml文件的Build Action更改为Resource

添加对.NET程序集UIAutomationTypes的引用。

编译并运行。

您不能使用设计器添加事件处理程序。只需在代码后台手动添加它们。

在StackOverflow上发布完整演示可能不是最好的选择,特别是如果这会引发更多相同类型的问题。如果有其他更好的地方,例如此类事物的公共存储库,请告诉我。


Bent,非常感谢你!今天是我的生日,你的回复是我收到的最好的礼物。你的答案简单易懂,步骤清晰,而且真的很有效。现在我需要学习它,并看看是否可以将其应用于WPF中的菜单和对话框。再次感谢。 - Bob McCrory
谢谢,Bob。如果你需要帮助控件、如何添加窗口图标、应用程序图标以及其他可能的东西,那就再问我吧。大部分都像C#一样,但是那些特定于F#的部分可能很难在谷歌上找到。 - Bent Tranberg
哦,还有 - 鲍勃生日快乐! - Bent Tranberg
1
我在这里添加了更多的材料:http://stackoverflow.com/documentation/f%23/9008/f-wpf-code-behind-application-with-fsxaml - Bent Tranberg
1
我在一个Spirograph应用程序中添加了我的解决方案,网址是:http://stackoverflow.com/documentation/f%23/9145/using-f-wpf-fsxaml-a-menu-and-a-dialog-box#t=201702200527195231483 - Bob McCrory

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接