在 WinForms 中可以使用 MessageBox.Show() 來快速建立訊息視窗,在 WinUI3 則是使用 ContentDialog
可以不要有 Title, Content, PrimaryButtonText ,但是只要是桌面應用程式,一定要指定 XamlRoot ,不然會拋出下列錯誤:
(不過如果沒有按鈕會無法關閉對話視窗,所以還是要放個按鈕,只是沒有按鈕不會拋出例外)
參考資料:
Microsoft.Learn - ContentDialog
最基礎 ContentDialog 範例
使用時需要注意 namespace ,正確是要 using Microsoft.UI.Xaml.Controls ,而筆者使用到 ABI.Microsoft.UI.Xaml.Controls ,一開始卡關超久...
var dialog = new ContentDialog
{
XamlRoot = this.Content.XamlRoot,
Title = "標題",
Content = "訊息",
PrimaryButtonText = "確定",
};
await dialog.ShowAsync();
可以不要有 Title, Content, PrimaryButtonText ,但是只要是桌面應用程式,一定要指定 XamlRoot ,不然會拋出下列錯誤:
System.ArgumentException: Value does not fall within the expected range.
at WinRT.ExceptionHelpers.<ThrowExceptionForHR>g__Throw|20_0(Int32 hr)
at WinRT.ExceptionHelpers.ThrowExceptionForHR(Int32 hr)
at ABI.Microsoft.UI.Xaml.Controls.IContentDialogMethods.ShowAsync(IObjectReference _obj)
at Microsoft.UI.Xaml.Controls.ContentDialog.ShowAsync()
at WinUiAppNotificationTest.MainWindow.myButton_Click(Object sender, RoutedEventArgs e) in C:\Users\ruyut\Documents\RiderProjects\2023\test\WinUiAppNotificationTest\WinUiAppNotificationTest\MainWindow.xaml.cs:line 74
at WinRT._EventSource_global__Microsoft_UI_Xaml_RoutedEventHandler.EventState.<GetEventInvoke>b__1_0(Object sender, RoutedEventArgs e)
at ABI.Microsoft.UI.Xaml.RoutedEventHandler.Do_Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr e)
(不過如果沒有按鈕會無法關閉對話視窗,所以還是要放個按鈕,只是沒有按鈕不會拋出例外)
ContentDialog 完整範例
var dialog = new ContentDialog
{
XamlRoot = this.Content.XamlRoot,
Title = "標題",
Content = "訊息",
PrimaryButtonText = "儲存", // 主要按鈕
SecondaryButtonText = "不儲存", // 次要按鈕
CloseButtonText = "取消", // 關閉按鈕
DefaultButton = ContentDialogButton.Primary, // 指定預設的按鈕
};
// 設定按下按鈕後的事件
dialog.PrimaryButtonClick += (_s, _e) =>
{
// TODO:
};
dialog.SecondaryButtonClick += (_s, _e) =>
{
// TODO:
};
dialog.CloseButtonClick += (_s, _e) =>
{
// TODO:
};
await dialog.ShowAsync();
參考資料:
Microsoft.Learn - ContentDialog
留言
張貼留言
如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com