由于我是盲人并且无法访问 Visual Studio,我可以只使用纯代码创建 C# WPF 应用程序吗?

Since I'm blind and Visual Studio isn't accessible, can I create C# WPF applications just with plain code?

我完全失明了,我使用 NVDA 屏幕 reader 来操作系统,我正在尝试创建一个 Windows 桌面应用程序。 Visual Studio 不是屏幕-reader 友好的,至少不是表单设计器部分。 VS Code 非常易于访问,尽管 powershell 的 protools 设计器不是。

每当我看到有关使用纯代码在 WPF 中编写 GUI 的问题时,我都会发现很多“以上帝的名义你为什么要这样做?使用 VS!”答案。好吧,原因就在这里,VS表单设计器对于盲人程序员来说是遥不可及的,所以最不实用的方法就得做。

那么,可以吗?您会对此提出任何资源或方法建议吗?

是的。你只能用代码来做 WPF。

这是来自 http://www.java2s.com/Tutorial/CSharp/0470__Windows-Presentation-Foundation/CodeOnlyWPFApplicationSample.htm

的简单示例
using System;
using System.Windows;
using System.Windows.Controls;

  public class App : Application {

    protected override void OnStartup(StartupEventArgs e) {
      base.OnStartup(e);
      MainWindow window = new MainWindow();
      window.Show();
    }

    [STAThread]
    public static void Main()
    {
        App app = new App();
        app.Run();
    }
  }

  public class MainWindow : Window {

    protected override void OnInitialized(EventArgs e) {
      base.OnInitialized(e);
      Button closeButton = new Button();
      closeButton.Content = "Close";
      this.Content = closeButton;
      closeButton.Click += delegate {
        this.Close();
      };
    }
  }

此外,使用 WinForms 可能更容易,因为它使用 C# 作为代码隐藏,并且更少 XML。

我将尝试从另一个示例开始构建,以获得可编译的代码。要使 WPF 正常工作,您需要一个使用 WPF 支持构建的项目。

最简单的方法是自己创建一个 .csproj 并使用之前发布的纯代码解决方案。

因此,从最小的 App.csproj 文件开始:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net5.0-windows</TargetFramework>
    <UseWPF>true</UseWPF>
  </PropertyGroup>
</Project>

然后是 App.cs 中的应用程序和 window 代码。我已经向它添加了几个控件,因为如果您想稍后开始添加更多内容,无论如何您都需要一个容器(我使用 StackPanel)。

using System;
using System.Windows;
using System.Windows.Controls;

public class App : Application {
    protected override void OnStartup(StartupEventArgs e)     {
        base.OnStartup(e);
        new MainWindow().Show();
    }

    [STAThread]
    public static void Main() => new App().Run();
}

public class MainWindow : Window {
    protected override void OnInitialized(EventArgs e) {
        base.OnInitialized(e);

        var panel = new StackPanel();
        this.Content = panel;

        var label = new Label { Content = "Click me:" };
        panel.Children.Add(label);
        
        var closeButton = new Button { Content = "Close", Height = 100 };
        closeButton.Click += (sender, args) => this.Close();
        panel.Children.Add(closeButton);

        (this.Width, this.Height) = (200, 200);
    }
}

然后使用 dotnet build 构建整个项目。您可以 运行 使用 dotnet run 或直接调用 exe。

或者,如果您想使用单独的 .xaml 和 .xaml.cs 代码探索 WPF 项目,您可以使用 dotnet new wpf -o MyProjectName 创建项目。这将生成一个项目、一个基于 xaml 的应用程序和一个基于 xaml 的表单。