You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinUI 3多页面项目保存文件时出现“指定转换无效”错误

WinUI 3 多页面项目中 FileSavePicker 初始化失败的解决方法

问题原因

单页面应用中,this指向主窗口实例,调用WindowNative.GetWindowHandle(this)能正常获取窗口句柄;但在多页面项目的第二页中,this是Page实例而非Window,直接调用该方法会抛出异常。

解决方案

先获取当前页面所属的窗口实例,再通过窗口获取句柄初始化FileSavePicker,修正后的代码如下:

private async void SaveButton_Click(object sender, RoutedEventArgs e)
{
    FileSavePicker savePicker = new FileSavePicker();

    // 获取当前页面所在的窗口实例
    var window = Window.GetWindow(this);
    if (window == null)
    {
        // 可添加窗口获取失败的提示逻辑
        return;
    }
    var hWnd = WindowNative.GetWindowHandle(window);

    InitializeWithWindow.Initialize(savePicker, hWnd);

    savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
    savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt", ".rtf" });
    var enteredFileName = "My Document";
    savePicker.SuggestedFileName = enteredFileName;

    StorageFile file = await savePicker.PickSaveFileAsync();
    if (file != null)
    {
        Windows.Storage.Streams.IRandomAccessStream randAccStream =
            await file.OpenAsync(FileAccessMode.ReadWrite);

        ScratchPad.Document.SaveToStream((TextGetOptions)Windows.UI.Text.TextGetOptions.None, randAccStream);
    }
}

关键说明

  • Window.GetWindow(this)可从当前Page控件追溯到所属的Window实例
  • 必须判断window是否为null,避免空引用异常
  • 确保已引入必要命名空间:using Microsoft.UI.Xaml;、using Microsoft.UI.Xaml.Windowing;、using WinRT.Interop;

内容的提问来源于stack exchange,提问作者therealchriswoodward

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 02:59:52