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

如何在后台代码中获取ResourceDictionary的x:Name属性?

获取ResourceDictionary的名称标识

当你通过Source属性引用外部ResourceDictionary时,XAML中的x:Name不会被映射到后台ResourceDictionary实例的属性上——因为ResourceDictionary本身没有内置的Name依赖属性,x:Name仅作为XAML内部元素的命名标识,跨文件引用时不会保留这个值。所以你没法直接通过Application.Current.Resources.MergedDictionaries[1].???的方式获取原XAML里的x:Name。

下面是两种可行的解决方案:

方案一:自定义带名称属性的ResourceDictionary子类

  1. 创建自定义的ResourceDictionary子类,添加用于存储名称的属性:
using System.Windows;

namespace WpfApp1
{
    public class NamedResourceDictionary : ResourceDictionary
    {
        public string DictionaryName { get; set; }
    }
}
  1. 在资源字典XAML中使用这个子类并设置DictionaryName:
<local:NamedResourceDictionary DictionaryName="DefaultLight"
                                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                                xmlns:local="clr-namespace:WpfApp1">
    <!-- 放置你的资源内容 -->
</local:NamedResourceDictionary>
  1. 修改App.xaml中的引用,使用自定义子类:
<Application x:Class="WpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp1"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/MyLib;component/Resources/OutgoingResources.xaml"/>
                <local:NamedResourceDictionary Source="/MyLib;component/Resources/Themes/DefaultDark.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>
  1. 后台代码中强转后获取名称:
var mergedDict = Application.Current.Resources.MergedDictionaries[1];
if (mergedDict is NamedResourceDictionary namedDict)
{
    Console.WriteLine(namedDict.DictionaryName);
}

方案二:在ResourceDictionary中添加标识资源

无需自定义类,直接在资源字典里添加一个存储名称的字符串资源:

  1. 在资源字典XAML中添加字符串资源(需引入system命名空间):
<ResourceDictionary x:Name="DefaultLight"
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:system="clr-namespace:System;assembly=mscorlib">
    <system:String x:Key="DictionaryName">DefaultLight</system:String>
    <!-- 其他资源内容 -->
</ResourceDictionary>
  1. 后台代码中通过资源Key获取名称:
var targetDict = Application.Current.Resources.MergedDictionaries[1];
if (targetDict.TryGetValue("DictionaryName", out var nameValue) && nameValue is string dictName)
{
    Console.WriteLine(dictName);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 16:32:51