这里是指新的桌面开发框架WinUI3,WinUI2只是UWP的一个库。
主要介绍了我在开发中遇到的常见的功能在WinUI3中不同与WPF或UWP的使用方式的写法。
文件选择器
WPF:OpenFileDialog
OpenFileDialog openFileDialog = new OpenFileDialog();
bool? result = openFileDialog.ShowDialog();
if (result.HasValue&&result.Value) {
FileName.Text = openFileDialog.FileName;
} else {
FileName.Text= null;
}
UWP:FileOpenPicker
FileOpenPicker picker = new FileOpenPicker();
picker.FileTypeFilter.Add("*");
StorageFile file = await picker.PickSingleFileAsync();
if (file!=null) {
FileName.Text=file.Name;
} else {
FileName.Text = "";
}
WinUI:FileOpenPicker
FileOpenPicker fileOpenPicker = new FileOpenPicker();
IntPtr hwnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
WinRT.Interop.InitializeWithWindow.Initialize(fileOpenPicker, hwnd);
fileOpenPicker.FileTypeFilter.Add("*");
StorageFile file = await fileOpenPicker.PickSingleFileAsync();
if (file != null) {
FileName.Text = file.Name;
} else {
FileName.Text = "";
}
异步线程更新UI
WPF:InvokeAsync
await Dispatcher.InvokeAsync(() => { MyTextBlock.Text = "123"; });
UWP:RunAsync
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { MyTextBlock.Text = "123"; });
WinUI:TryEnqueue
DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, () => { MyTextBlock.Text = "123"; });