WinUI 3中ContentDialog含TextBox却显示为空的问题排查
基于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。无论添加什么UI控件都无法显示,这是为什么?

问题原因
你错误地将继承自ContentDialog的MyContentDialog作为另一个ContentDialog的Content属性值,形成了ContentDialog嵌套结构。这种嵌套会导致内部控件无法正确渲染,最终对话框显示为空。
解决方法
有两种可行的修正方案:
方案1:直接使用自定义的MyContentDialog
不需要新建外层ContentDialog,直接实例化MyContentDialog并设置属性后显示:
private async void MyMenu_Click(object sender, RoutedEventArgs e) { MyContentDialog dialog = new MyContentDialog() { XamlRoot = this.Content.XamlRoot, Title = "My Dialog", PrimaryButtonText = "OK", CloseButtonText = "Cancel" }; ContentDialogResult result = await dialog.ShowAsync(); }
方案2:将MyContentDialog改为UserControl
如果要保留外层ContentDialog的结构,可将MyContentDialog的基类改为UserControl,调整代码如下:
代码后置文件:
namespace myapp { public sealed partial class MyContentControl : UserControl { public MyContentControl() { this.InitializeComponent(); } } }
XAML代码:
<UserControl x:Class="myapp.MyContentControl" 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> </UserControl>
菜单点击事件代码(仅修改Content实例):
private async void MyMenu_Click(object sender, RoutedEventArgs e) { ContentDialog dialog = new ContentDialog() { XamlRoot = this.Content.XamlRoot, Title = "My Dialog", Content = new MyContentControl(), PrimaryButtonText = "OK", CloseButtonText = "Cancel" }; ContentDialogResult result = await dialog.ShowAsync(); }
内容的提问来源于stack exchange,提问作者Ethan Allen
相关产品推荐
相关产品推荐

