windows 为什么我的XAML中有一个文本框,但WinUI 3中的ContentDialog显示为空?

vqlkdk9b  于 2023-03-04  发布在  Windows
关注(0)|答案(2)|浏览(147)

使用C#的WinUI 3:

我有一个应用的主Window类,当单击菜单时,它会显示一个简单的对话框:

private async void MyMenu_Click(object sender, RoutedEventArgs e)
{
    ContentDialog dialog = new ContentDialog()
    {
        XamlRoot = this.Content.XamlRoot,
        Title = "My Dialog",
        Content = new MyContentDialog(),
        PrimaryButtonText = "OK",
        CloseButtonText = "Cancel"
    };
    ContentDialogResult result = await dialog.ShowAsync();
}

以下是MyContentDialog类的代码隐藏:

namespace myapp
{
    public sealed partial class MyContentDialog : ContentDialog
    {
        public MyContentDialog()
        {
            this.InitializeComponent();
        }
    }
}

下面是MyContentDialog类的XAML:

<ContentDialog
    x:Class="myapp.MyContentDialog"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:myapp"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">

    <Grid>
        <TextBox x:Name="MyTextBox" />
    </Grid>
</ContentDialog>

看起来很简单,对吧?那么为什么我的对话框看起来像这样,里面没有TextBox呢?不管我向XAML添加什么UI控件,我都无法显示任何内容。为什么?

6l7fqoea

6l7fqoea1#

您已经在此处设置了Content

<ContentDialog
    x:Class="myapp.MyContentDialog"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:myapp"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Style="{StaticResource DefaultContentDialogStyle}">

    <!-- Content -->
    <Grid>
        <TextBox x:Name="MyTextBox" />
    </Grid>

</ContentDialog>

因此,您在这里覆盖了Content,您只需要删除设置Content的代码。

MyContentDialog dialog = new()
{
    XamlRoot = this.Content.XamlRoot,
    Title = "My Dialog",
    //Content = new MyContentDialog(), 
    PrimaryButtonText = "OK",
    CloseButtonText = "Cancel"
};
mnowg1ta

mnowg1ta2#

用户Andrew KeepCoding用他的部分答案引导我找到了正确的方向,但下面是完全正确的代码。
我需要直接调用MyContentDialog类作为对话框,删除Content = new MyContentDialog()行,然后添加一行来更新样式,使其看起来像默认样式。

MyContentDialog dialog = new MyContentDialog()
{
    XamlRoot = this.Content.XamlRoot,
    Style = Application.Current.Resources["DefaultContentDialogStyle"] as Style,
    Title = "My Dialog",
    PrimaryButtonText = "OK",
    CloseButtonText = "Cancel"
};
ContentDialogResult result = await dialog.ShowAsync();

相关问题