在 FsXaml 中最小化 WPF window

Minimising a WPF window in FsXaml

我正在尝试将此用于最小化 WPF window 的 C# (WPF MVVM) 代码转换为 F#/FsXaml。

using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = DependencyInjector.Retrieve<MainWindowViewModel>();
        }
        
        //... some generated code

        private void OnKeyDownHandler(object sender, System.Windows.Input.KeyEventArgs e)
            => this.WindowState = (e.Key == Key.Escape) ? (WindowState)FormWindowState.Minimized : (WindowState)FormWindowState.Normal;
    }

如何将带有OnKeyDownHandler的C#代码转换成F#/FsXaml(只有code behind,没有MVVM)?

我曾尝试在 F#/FsXaml 中创建等效代码,但没有成功 - 见下文。

open System.Windows.Input
type MainWindowXaml = FsXaml.XAML<"XAMLAndCodeBehind/MainWindow.xaml">

type MainWindow() as this =
    inherit MainWindowXaml() 
    
    //... some code  
   
    let MyOnKeyDownHandler (e: System.Windows.Input.KeyEventArgs) = 
        match (e.Key = Key.Escape) with 
        | true  -> this.WindowState <- Windows.WindowState.Minimized
        | false -> this.WindowState <- Windows.WindowState.Normal
    
    do        
        this.KeyDown.Add MyOnKeyDownHandler 

带有 type MainWindow() 的行给出了这两个错误:

'MainWindowXaml.OnKeyDownHandler(sender: obj, e: KeyEventArgs) : unit'

没有实现

这种类型是 'abstract' 因为一些抽象成员还没有被赋予实现。如果这是有意的,则将“[]”属性添加到您的类型中。

两个相关的 xaml 文件(在 C# 和我的 F# 尝试中)都在 DataContext 部分包含 KeyDown="OnKeyDownHandler"

编辑: 添加了 XAML 文件的相关部分:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Icon= ......
    KeyDown="OnKeyDownHandler"
    WindowStartupLocation="CenterScreen"
    Title="...">
    <Canvas Margin="0,0,2,2">
      //... some XAML code...
    </Canvas>
</Window>

我没有直接使用 FsXaml 的经验,但您使用的模式似乎与 WpfSimpleMvvmApplication sample. Here, the xaml file defines an event handler OnFullNameDoubleClick. This then becomes an abstract method in the generated class that needs to be overriden in the corresponding F# source file.

中的模式相似

这意味着您的 OnKeyDownHandler(可能在您的问题中未包含的 XAML 文件中定义)需要定义为覆盖方法(并且 FsXaml 会自动附加事件处理程序):

open System.Windows.Input
type MainWindowXaml = FsXaml.XAML<"XAMLAndCodeBehind/MainWindow.xaml">

type MainWindow() =
    inherit MainWindowXaml() 
    
    //... some code  
   
    override this.OnKeyDownHandler(_:obj, e: System.Windows.Input.KeyEventArgs) = 
        match (e.Key = Key.Escape) with 
        | true  -> this.WindowState <- Windows.WindowState.Minimized
        | false -> this.WindowState <- Windows.WindowState.Normal

编辑:我还从 class 定义中删除了 as this,因为不再需要它了——您可以通过方法定义访问 this(这有点简单).