简体   繁体   中英

How do I solve this System.InvalidCastException in WinUI3 while trying to get the window handler?

I am developing an application in WinUI 3 and I need to open a folder picker dialog. To do so I visited the documentation and GitHub pages and this is what I wrote (PrincipalPage.xaml.cs):

(...)
private async void Select_Click(object sender, Microsoft.UI.Xaml.RoutedEventArgs e)
{
    var task = SelectFile();
    await task;
}

public async Task SelectFile()
{
    var folderPicker = new FolderPicker();
    var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
    WinRT.Interop.InitializeWithWindow.Initialize(folderPicker, hwnd);
    folderPicker.FileTypeFilter.Add("*");
    var file = await folderPicker.PickSingleFolderAsync();
    storePath = file.Path;
    DestinationURLTextBox.Text = file.Path;
}
(...)

在此处输入图像描述

I tried to find what I'm doing wrong, and even tried to put the code under the button click method directly but nothing changed.

Is this an external config thing or... just something I'm doing wrong?

Since this code is in a Page (PrincipalPage.xaml.cs), you are passing a Page to GetWindowHandle . You need to pass a Window .

You can do it this way.

App.xaml.cs

public partial class App : Application
{
    public Window? MainWindow { get; private set; }

    public App()
    {
        this.InitializeComponent();
    }

    protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
    {
        MainWindow = new MainWindow();
        MainWindow.Activate();
    }
}

PrincipalPage.xaml.cs

public sealed partial class PrincipalPage: Page
{
    public BlankPage1()
    {
        this.InitializeComponent();
    }

    private async void Select_Click(object sender, RoutedEventArgs e)
    {
        var task = SelectFile();
        await task;
    }

    public async Task SelectFile()
    {
        var folderPicker = new FolderPicker();

        var mainWindow = (App.Current as App)?.MainWindow;
        var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(mainWindow);

        WinRT.Interop.InitializeWithWindow.Initialize(folderPicker, hwnd);
        folderPicker.FileTypeFilter.Add("*");
        var file = await folderPicker.PickSingleFolderAsync();
        storePath = file.Path;
        DestinationURLTextBox.Text = file.Path;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM