如何创建对话框
若要创建对话框,你使用 ContentDialog 类。 你可以使用代码或标记创建对话框。 尽管使用 XAML 定义 UI 元素通常更容易,但对于简单对话框,实际上只使用代码更容易。
三个对话框按钮
ContentDialog 有三种不同类型的按钮可用于构建对话框体验。
- CloseButton - 必需 - 表示允许用户退出对话框的安全、无破坏性操作。 显示为最右侧的按钮。
- PrimaryButton - 可选 - 表示第一个“执行”操作。 显示为最左侧的按钮。
- SecondaryButton - 可选 - 表示第二个“执行”操作。 显示为中间的按钮。
private async void myButton_Click(object sender, RoutedEventArgs e)
{
ContentDialog noWifiDialog = new ContentDialog
{
Title = "Subscribe to App Service?",
Content = "Listen, watch, and play in high definition for only $9.99/month. Free to try, cancel anytime.",
CloseButtonText = "Not Now",
PrimaryButtonText = "Subscribe",
SecondaryButtonText = "Try it",
//设置默认按钮
DefaultButton= ContentDialogButton.Primary,
};
//必须设置XamlRoot,否则会报错误:Value does not fall within the expected range.
if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8))
{
noWifiDialog.XamlRoot =this.Content.XamlRoot;
}
ContentDialogResult result = await noWifiDialog.ShowAsync();
if (result == ContentDialogResult.Primary)
{
mybtn.Content = "主按钮";
}
else if(result == ContentDialogResult.Secondary)
{
mybtn.Content = "次按钮";
}
else
{
mybtn.Content = "取消";
}
}
警告
每次只能在每个线程中打开一个 ContentDialog。 尝试打开两个 ContentDialog 会引发异常,即使尝试在独立的 AppWindow 中打开。