WPF XAML Window无法正常显示子弟你自定义UserControl,但编译能通过

问题遇到的现象和发生背景

使用Visual Studio编写WPF XAML时,将自定义的UserControl添加到Window中时,UserControl无法显示,但编译能通过

img

img

操作环境、软件版本等信息

win11 VisualStudio2022 WPF

我想要达到的结果

Window中能正常显示这些自定义的UserControl。

你贴的第三个图不是把错误原因写的很清楚吗,就是有个文件找不到导致设计器显示不出来。
编译能通过很正常,代码本身没有错误。

抛异常那段加个try catch吧,估计是去windows这些系统文件里面去找资源了

【以下回答由 GPT 生成】

回答:

这个问题可能出现在几个方面,包括以下: 1. UserControl的属性没有正确设置。 2. UserControl的父元素没有正确设置。 3. UserControl的布局有误。

为了解决这个问题,可以按照以下步骤逐一排查。

步骤 1:检查UserControl的属性

首先,确保你的UserControl的属性设置正确。主要关注的属性包括WidthHeightVisibilityBackground等。确保这些属性没有被设置为0或透明。

<UserControl x:Class="YourUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Width="200" Height="200" Visibility="Visible" Background="White">
    <!-- 添加你的UserControl的内容 -->
</UserControl>

步骤 2:检查UserControl的父元素

确保你在将UserControl添加到Window中时,将其放置在正确的父元素中。通常情况下,你应该将UserControl放置在Grid或其他容器中。

<Window x:Class="YourWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <!-- 其他控件 -->
        <local:YourUserControl/>
    </Grid>
</Window>

请注意,这里的local是指向你的UserControl所在命名空间的引用,你需要根据实际情况进行调整。

步骤 3:检查UserControl的布局

确保你在UserControl中正确设置了布局。例如,使用Grid、StackPanel等进行布局,并为子元素设置正确的行列等属性。

<UserControl x:Class="YourUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Width="200" Height="200" Visibility="Visible" Background="White">
    <Grid>
        <Button Content="Button" Width="100" Height="40"/>
    </Grid>
</UserControl>

如果你的布局是复杂的,可能需要进一步检查布局中的其他属性和嵌套关系。

以上是我给出的一些排查步骤,希望能帮助你解决问题。如果你遇到了其他问题,或者以上步骤没有解决你的问题,请提供更多的细节和代码,以便我能够更好地帮助你。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^