我需要一個背景透明的 ContentDialog,像下圖一樣。如何定制?寫了一個簡單的示例(https://github.com/ZhangGaoxing/uwp-demo/tree/master/ContentDialogDemo)
首先在項目里新建一個資源字典,並在 App.xaml 添加以下代碼將此資源字典合並
<Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Style.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources>
這時新添加的資源字典還是空的,我們需要找到 ContentDialog 的默認樣式。這些默認樣式在已安裝的 Windows 10 SDK 中被提供,比如 SDK 默認安裝在 C 盤的時候,控件樣式字典 generic.xaml 可以在 C:\Program Files (x86)\Windows Kits\10\DesignTime\CommonConfiguration\Neutral\UAP\10.0.14393.0\Generic 這里找到。找到后用 Visual Studio 打開,如下圖。
接下來按 Ctrl+F 搜索 ContentDialog 找到默認樣式復制到剛才新建的資源字典中,然后根據需要定制樣式即可。
像我需要的透明 ContentDialog 只需要更改 Property 為 Background 的 Value 值為 Transparent 即可。注意不要忘記給一個 x:Key 值,也就是起個名稱,這里為 x:Key="TransparentDialog" 。
樣式定制完成,並且資源字典也合並完成,下面就是要在代碼中去調用了。資源字典的調用也是靠鍵值對,輸入對應的鍵來返回對應的值。
在項目合適的位置新建一個 Style 類型的字段,用來獲取樣式。
Style transparent = (Style)Application.Current.Resources["TransparentDialog"];
樣式獲取完成后設置 ContentDialog 的 Style 屬性即可
var contentDialog = new ContentDialog() { Content = new Content("This is a transparent ContentDialog."), PrimaryButtonText = "確定", FullSizeDesired = false }; contentDialog.Style = transparent; contentDialog.PrimaryButtonClick += (_s, _e) => { contentDialog.Hide(); }; await contentDialog.ShowAsync();
這樣,一個定制樣式的 ContentDialog 就完成了。