How can I use WPF menus and dialog boxes in F#?

﹥>﹥吖頭↗ 提交于 2019-12-07 08:38:37

问题


I've been trying to find an example of using XAML and F# - without C# - to set up traditional menus and dialog boxes. Everything I can find online either uses C# or it is old, before the most recent versions of F# and .NET. Can anyone suggest an example I can look at? Thanks.


回答1:


When you try to learn WPF, you come across many C# examples based on "good old" code behind rather than MVVM or MVC. The following explains how to quickly create an F# WPF code behind application. Using this, it becomes easier to experiment with all those examples.

Create an F# console application.

Change the Output type of the application to Windows Application.

Add FsXaml from NuGet.

Add these four source files, and arrange them in this order.

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.

Delete the Program.fs file.

Change the Build Action to Resource for the two xaml files.

Add a reference to the .NET assembly UIAutomationTypes.

Compile and run.

You can't use the designer to add event handlers. Simply add them manually in the code behind.

StackOverflow is possibly not the best place to post complete demos like this one, especially if this spins off more questions along the same line. If there is another better place, e.g. a public repo for this kind of thing, please let me know.



来源:https://stackoverflow.com/questions/41917667/how-can-i-use-wpf-menus-and-dialog-boxes-in-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!