即使在导入 Win32 命名空间后,SaveFileDialog 在 UWP 中也不起作用

SaveFileDialog is not working in UWP even after import Win32 namespace

我正在尝试使用 UWP 和 XAML 在 C# 中使用 SaveFileDialog 创建一个保存按钮。

我试过像 this post 所说的那样导入 Microsoft.Win32,但是没有用。 SaveFileDialog() 函数告诉我:

Error CS0234 The type or namespace name 'SaveFileDialog' does not exist in the namespace 'Microsoft.Win32' (are you missing an assembly reference?)

这是我的代码:

Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = "Document";
            dlg.DefaultExt = ".txt";
            dlg.Filter = "Text documents (.txt)|*.txt";

我该如何解决这个问题?

您好,您需要从 soultion Explorer 添加引用 Windows.Forms 右键单击​​解决方案资源管理器中的引用,然后单击添加引用并添加系统。Windows.Forms 添加到您的项目后,您可以添加系统.Windows.Forms 到您的命名空间

using System.Windows.Forms;

之后您可以使用 SaveFileDialog

我用这种方式 我的代码:

 SaveFileDialog save = new SaveFileDialog();
            Nullable<bool> result = save.ShowDialog();
            if (result==true)
            {
              //Your Code here 
          
            }

我在 WPF 项目中使用的命名空间代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;
using System.IO;
using Microsoft.Win32;
using System.Windows.Forms;
using System.Threading;

与其遵循 UWP 预览时提供的非常古老的建议,不如按照自己的方式阅读当前的 MS Docs 文章,这些文章为许多常见的应用程序范例提供了非常简单的示例。

As a general rule, if you are starting out to develop a new application today, and you have chosen UWP, then you should try to avoid bringing in direct references to the Win32 or the old .Net runtimes. While you can make it work, the backward compatibility is designed to support developers moving legacy code over to .Net Core, for many controls there will already be a native Xaml or WinUI implementation.

看看使用 FileSavePicker

// Create the dialog, this block is equivalent to OPs original code.
var savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.SuggestedStartLocation =
    Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
// Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = "Document";

// Show the dialog for the user to specify the target file
// The dialog will return a reference to the file if they click on "save"
// If the user cancels the dialog, null will be returned
Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
    // Prevent updates to the remote version of the file until
    // we finish making changes and call CompleteUpdatesAsync.
    Windows.Storage.CachedFileManager.DeferUpdates(file);
    // write to file
    await Windows.Storage.FileIO.WriteTextAsync(file, file.Name);
    // Let Windows know that we're finished changing the file so
    // the other app can update the remote version of the file.
    // Completing updates may require Windows to ask for user input.
    Windows.Storage.Provider.FileUpdateStatus status =
        await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);
    if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
    {
        System.Diagnostics.Debug.WriteLine("File " + file.Name + " was saved.");
    }
    else
    {
        System.Diagnostics.Debug.WriteLine("File " + file.Name + " couldn't be saved.");
    }
}
else
{
    System.Diagnostics.Debug.WriteLine("User cancelled the save dialog.");
}

如果您刚刚开始使用 UWP,请确保您获得以下应用程序和项目:

  • XAML Controls Gallery
    这是您获得 OOTB 的所有控件的一站式商店,从这里开始!
  • Windows App Studio UWP Samples
    允许您查看和调整 Windows App Studio UWP 控件和数据源库的组件。使用此应用程序,您可以浏览不同的控件、编辑属性以实时查看更改,甚至可以复制 XAML、C# 和 JSON 代码。该应用程序的目的是突出显示 Windows App Studio 库中的内容。
  • Windows Community Toolkit Sample App
    这是一个 link 编译示例应用程序,这是一个新的、有时是实验性控件的集合,您可以在 UWP 应用程序中使用它们。
  • Get Windows App Samples
    这是一个不断增长的 GitHub 存储库,演示了如何让 UWP 为您工作。

根据SaveFileDialog Class的文档,提到API适用于.NET Core 3.0和3.1。但 UWP 目前只支持 .NET Core 2.0。这就是为什么你遇到这个意外。您发布的 link 是一个 WPF 问题,它可能不适合 UWP。

@Chris Schaller 的解决方案是正确的,您可以尝试 FileSavePicker