WinUI 3 C#中如何为Page获取HWND以初始化文件选择器
如何在WinUI 3的Page中获取窗口句柄以初始化文件选择器
在空白WinUI 3项目的Window中能正常获取HWND并初始化文件选择器,但在Page中直接调用WindowNative.GetWindowHandle(this)会报错——因为Page并未实现WindowNative接口。以下是正确的解决方式:
解决逻辑
- 先找到当前Page所属的Window实例
- 从Window实例中提取HWND
- 用该句柄完成文件选择器的初始化
可以实现一个简单的辅助方法来获取元素所属的Window:
public static Window GetWindowForElement(FrameworkElement element) { var parent = element.Parent; while (parent != null && !(parent is Window)) { parent = ((FrameworkElement)parent).Parent; } return parent as Window; }
修正后的完整代码
public sealed partial class uploadingUVPage : Page { public uploadingUVPage() { this.InitializeComponent(); } private async void PickAFileButton_Click(object sender, RoutedEventArgs e) { var openPicker = new Windows.Storage.Pickers.FileOpenPicker(); // 获取当前Page所在的Window实例 var window = GetWindowForElement(this); // 从Window实例中获取HWND IntPtr hWnd = WinRT.Interop.WindowNative.GetWindowHandle(window); WinRT.Interop.InitializeWithWindow.Initialize(openPicker, hWnd); openPicker.ViewMode = PickerViewMode.Thumbnail; openPicker.FileTypeFilter.Add("*"); var file = await openPicker.PickSingleFileAsync(); if (file != null) { PickAFileOutputTextBlock.Text = "Picked file: " + file.Name; } else { PickAFileOutputTextBlock.Text = "Operation cancelled."; } } // 辅助方法:查找元素所属的Window private Window GetWindowForElement(FrameworkElement element) { var parent = element.Parent; while (parent != null && !(parent is Window)) { parent = ((FrameworkElement)parent).Parent; } return parent as Window; } }
注意事项
- 确保调用
GetWindowForElement时,Page已经被加载到Window中(比如按钮点击事件触发时,Page已完成渲染,此时可以正常获取到Window) - 如果项目中已有类似
WindowHelper的工具类,可直接复用其中的窗口查找逻辑
内容的提问来源于stack exchange,提问作者lezzka
相关产品推荐
相关产品推荐

