You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UWP应用中TeachingTip控件报错及App.xaml资源正确添加咨询

解决UWP中TeachingTip控件的资源配置与显示问题

我来帮你搞定这个TeachingTip的坑!从你描述的问题来看,核心问题出在App.xaml的资源配置方式,还有一个容易忽略的点是TeachingTip的放置位置。下面一步步给你解决:

第一步:正确配置App.xaml中的WinUI资源

你之前的错误在于没有把XamlControlsResources放在资源字典的合并集合里,导致资源无法全局加载。正确的配置应该是:

打开你的App.xaml,把XamlControlsResources添加到ResourceDictionary.MergedDictionaries中,作为第一个项(确保WinUI资源优先加载),不需要加x:Key。示例代码如下:

<Application
    x:Class="YourAppNamespace.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:YourAppNamespace">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <!-- 加载WinUI控件的全局样式与资源,必须放在MergedDictionaries里 -->
                <XamlControlsResources xmlns="using:Microsoft.UI.Xaml.Controls" />
                <!-- 这里可以添加你的其他自定义资源字典 -->
            </ResourceDictionary.MergedDictionaries>
            <!-- 你的本地应用资源可以写在这里 -->
        </ResourceDictionary>
    </Application.Resources>
</Application>

为什么之前的方式会报错?

  • 直接把XamlControlsResources放在Application.Resources根下:ResourceDictionary里的每一项都需要唯一键,而它本身是一个资源字典,直接放置会触发键冲突错误。
  • 添加x:Key="XamlControlsResources":这样资源字典不会被自动合并到全局资源中,TeachingTip需要的内置画笔(比如TeachingTipBackgroundBrush)就无法被找到,从而抛出XamlParseException。

第二步:调整TeachingTip的放置位置

你现在把TeachingTip放在了Button.Resources里,这是错误的!Resources集合里的元素不属于可视化树的一部分,TeachingTip需要被添加到页面的可视化树中才能正确渲染和绑定Target。

修改你的页面XAML,把TeachingTip移到根容器(比如Grid)下,示例代码:

<Grid>
    <Button x:Name="BackButton" Background="{x:Null}" Content="Back" Click="BackButton_Click"/>
    <Button x:Name="TeachingTipButton" Click="TeachingTipButton_OnClick" Content="Show Teaching Tip"/>
    
    <!-- 将TeachingTip放在可视化树中,确保它能被正确渲染 -->
    <controls:TeachingTip x:Name="ToggleThemeTeachingTip" 
                          Target="{x:Bind BackButton}" 
                          Title="Change themes without hassle" 
                          Subtitle="It's easier than ever to see control samples in both light and dark theme!" 
                          CloseButtonContent="Got it!"/>
</Grid>

第三步:验证其他环节

  1. 确认已经通过NuGet安装了最新版的Microsoft.UI.Xaml包(建议安装稳定版,比如2.8.1或更高)。
  2. 页面中已经正确导入WinUI命名空间:xmlns:controls="using:Microsoft.UI.Xaml.Controls"。
  3. 后台打开TeachingTip的逻辑没问题:
private void TeachingTipButton_OnClick(object sender, RoutedEventArgs e) {
    ToggleThemeTeachingTip.IsOpen = true;
}

按照上面的步骤调整后,再运行程序,点击按钮应该就能正常显示TeachingTip了!

内容的提问来源于stack exchange,提问作者Ramosta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:32:46