[英]How do I solve this System.InvalidCastException in WinUI3 while trying to get the window handler?
我正在 WinUI 3 中開發一個應用程序,我需要打開一個文件夾選擇器對話框。 為此,我訪問了文檔和 GitHub 頁,這就是我寫的內容 (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;
}
(...)
我試圖找到我做錯了什么,甚至試圖將代碼直接放在按鈕點擊方法下但沒有任何改變。
這是外部配置還是...只是我做錯了什么?
由於此代碼位於Page
(PrincipalPage.xaml.cs) 中,因此您將Page
傳遞給GetWindowHandle
。 您需要傳遞一個Window
。
你可以這樣做。
應用程序.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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.