如果从不同的 exe 调用,请使用具有相同密钥的不同 DataTemplate

Use a different DataTemplate with the same key if called from different exe

wpf.dll 中,我在 ResourceDictionary XAML:

中定义了一个带有键 MorphControl 的 DataTemplate
<ResourceDictionary>
       <DataTemplate x:Key="MorphControl">
        <n1:m1 />
    </DataTemplate>
</ResourceDictionary>

如果这个wpf.dll被一个exe调用(比如A.exe),那么我想上面的FindResource("MorphControl")到returnm1相关资源.

但是,wpf.dll 有可能被另一个 exe(比如 B.exe)调用,在 B.exe 中,同一个键被重新定义为使用另一个值,即在B.exe里面,存在这个定义:

<ResourceDictionary>
       <DataTemplate x:Key="MorphControl">
        <n2:m2 />
    </DataTemplate>
</ResourceDictionary>

所以当B.exe调用时,我想要FindResource["MorphControl"]到returnm2相关资源。

我想对 A.exeB.exe 使用相同的 wpf.dll。我不想将 MorphControl 定义从 wpf.dll 移动到 A.exe-- 它必须保持在 wpf.dll.

此外,这个特定的 Resource 键必须始终保持不变,因为在 wpf.dll 内部,我有一个我不想触及的 DataTemplateSelector 逻辑

如何做到这一点,或者这可能吗?

这是一种应该可行的非正统方法(我没有尝试过,但根据我所做的其他一些事情,它应该可行):

创建两个 ResourceDictionaries,一个用于两个单独文件中的每个 exe。 创建将继承 ResourceDictionary 的 class,我们称之为 ExeAwareDictionary。它应该是 ResourceDictionary 类型的私有 fields/properties 并且您应该覆盖 item[object] 属性。 当 getter for item 属性 被调用时,您可以检查它是哪个 exe(通过检查当前进程)和 return 具有来自适当 "inner" 的给定密钥的资源字典.

您可能还想覆盖其他一些属性,例如 KeysValues

我找到了我的答案(与 this answer 相同):首先定义 ResourceDictionary.MergeDictionarieswpf.dll DataTemplate,然后是 B.exe DataTemplate。换句话说:

<Application.Resources>
   <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                  <ResourceDictionary Source="wpf.dll.xaml"/>
                  <ResourceDictionary Source="B.exe.xaml"/>
            </ResourceDictionary.MergedDictionaries>
   </ResourceDictionary>
</Application.Resources>