WPF中App.xaml资源与合并字典的访问权限问题咨询
问题解答
核心结论
是的,App.xaml中合并的资源字典(此处为Generic.xaml)无法访问App.xaml自身定义的资源,且绝对不能在Generic.xaml中合并App.xaml——这会引发循环引用错误。
原因解析
WPF资源字典的合并遵循单向依赖规则:当字典A合并字典B时,A可以访问B的资源,但B无法反向访问A的资源。你当前的结构是App.xaml的主资源字典合并了Generic.xaml,Generic.xaml属于被合并的一方,自然无法回溯查找App.xaml里定义的Static.Background、Static.Primary等资源,这就是XamlParseException的根源——资源查找失败。
添加InitializeComponent()无法解决问题,因为这是WPF资源查找机制的固有规则,和初始化顺序无关。
可行解决方案
最合理的做法是将共享资源抽离到独立的公共资源字典,让App.xaml和Generic.xaml都合并这个公共字典,实现资源共享:
步骤1:创建共享资源字典
新建SharedResources.xaml文件,存放需要两边共用的资源:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <SolidColorBrush x:Key="Static.Background" Color="#121212"/> <SolidColorBrush x:Key="Static.Primary" Color="#34D9EB"/> </ResourceDictionary>
步骤2:修改App.xaml
移除原有的共享资源,改为合并公共字典,保留仅在App.xaml中使用的资源(比如Button的Style):
<Application x:Class="Test.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/xaml" xmlns:local="clr-namespace:Test.WPF"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <!-- 先合并共享字典,保证后续资源能引用到 --> <ResourceDictionary Source="/SharedResources.xaml"/> <ResourceDictionary Source="/Themes/Generic.xaml"/> </ResourceDictionary.MergedDictionaries> <!-- 保留仅App.xaml需要的资源 --> <Style TargetType="{x:Type Button}"> <Setter Property="Background" Value="{StaticResource Static.Primary}"/> <Setter Property="Margin" Value="0"/> <Setter Property="Padding" Value="0"/> </Style> </ResourceDictionary> </Application.Resources> </Application>
步骤3:修改Generic.xaml
合并共享字典,即可正常引用公共资源:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/SharedResources.xaml"/> </ResourceDictionary.MergedDictionaries> <!-- 此处可直接引用Static.Background、Static.Primary等资源 --> </ResourceDictionary>
其他可选方案
如果某些资源仅在Generic.xaml中使用,可以直接将这些资源移到Generic.xaml中;但如果App.xaml也需要使用这些资源,优先选择共享字典的方案,避免资源重复定义。
内容的提问来源于stack exchange,提问作者Caleb lee
相关产品推荐
相关产品推荐

