当您尝试学习 WPF 时,您会遇到许多基于“好旧”代码而不是 MVVM 或 MVC 的 C# 示例。下面介绍如何快速创建 F# WPF 代码隐藏应用程序。使用它,可以更轻松地试验所有这些示例。
创建 F# 控制台应用程序。
改变输出类型申请的Windows应用程序.
Add FsXaml来自 NuGet。
添加这四个源文件,并按此顺序排列。
主窗口.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>
主窗口.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>
应用程序.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.
删除程序文件 file.
改变构建行动 to Resource对于两个 xaml 文件。
添加对 .NET 程序集的引用UI自动化类型.
编译并运行。
您不能使用设计器添加事件处理程序。只需在后面的代码中手动添加它们即可。
StackOverflow 可能不是发布像这样的完整演示的最佳场所,特别是如果这会引发更多类似的问题。如果还有其他更好的地方,例如此类事情的公共回购,请告诉我。