WinUI3开发笔记(Ⅱ)

  • WinUI3中的”MessageBox.Show()

# (一,如何实现)

“开发WinUI3,第一个不适就是消息弹窗!”

WinUI中没有C#.NetFrameWork的MessageBox,但怎么实现弹窗呢?官方给出了方法

官方给出了示例代码,可在应用商店搜索”Xaml Controls Gallery”或前往官网-开发人员中心-查看示例可以下载示例(包括源代码)

image

点击查看xaml代码
<Page
    x:Class="AppUIBasics.ControlPages.ContentDialogContent"
    xmlns="//schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="//schemas.microsoft.com/winfx/2006/xaml">

    <StackPanel VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
        <!-- Content body -->
        <TextBlock Text="Lorem ipsum dolor sit amet, adipisicing elit." TextWrapping="Wrap" />
        <CheckBox Content="Upload your content to the cloud."/>
    </StackPanel>

</Page>
点击查看C#代码
private async void ShowDialog_Click(object sender, RoutedEventArgs e)
{
    ContentDialog dialog = new ContentDialog();
    dialog.Title = "Save your work?";
    dialog.PrimaryButtonText = "Save";
    dialog.SecondaryButtonText = "Don't Save";
    dialog.CloseButtonText = "Cancel";
    dialog.DefaultButton = ContentDialogButton.Primary;
    dialog.Content = new ContentDialogContent();

    var result = await dialog.ShowAsync();
}

C#代码是放置在事件中的,比如按钮点击时弹窗,则放入这一段,其中倒数第二条dialog.Content = new ContentDialogContent(); 则是连接的另一个xaml页面作为内容,去掉也可以的

效果如下:
image

当然,也可以放置其他内容,比如颜色选择,图片剪辑等,此处就不过多展示(因为颜色选择器本人还未弄懂)


(二,报错问题)

当我兴高采烈放到一个”Test”项目中尝试的时候,出错啦!

为什么出错呢?直接运行会直接导致闪退,使用调试的时候,看到了以下错误:
image
System.ArgumentException:“Value does not fall within the expected range.”
也就是值不在预期范围内,超范围了呗!
后来经过几个小时的不断尝试,我发现…

来自//blog.csdn.net/flyingdream123/article/details/122523347的博主给出了问题所在
image

也就是在var result = await dialog.ShowAsync();的前面需设置XamlRoot

点击查看代码
if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8))
            {
                dialog.XamlRoot = this.Content.XamlRoot;
            }

折腾了好久的问题终于解决了!官方竟然没给出这一段…[无语]😶


(三,获取点击的按钮)

如何判断用户点击了哪个按钮呢?
var result = await dialog.ShowAsync();则是获取了按钮值,判断方法如下:
image

点击查看代码
if (result == ContentDialogResult.Primary)
{
    //第一按钮"
}
else if (result == ContentDialogResult.Secondary)
{
    //第二按钮"
}
else
{
    //取消按钮
}

注意!前面的C#代码中设置按钮的片段中,取消按钮是必须的,其余按钮是可选的


特别说明:弹窗需要使用异步方法!

image

Tags: