在 DynamicResource 上使用 BasedOn 样式属性 [英] Using BasedOn Style Property on DynamicResources
问题描述
我想知道是否有一种方法可以将 wpf 样式的 basedOn 属性与动态资源一起使用.例如
i wonder if there is a way to use the basedOn property of wpf styles with dynamicresources. e.g.
<Style BasedOn="{DynamicResource somestyle}">
<Setter Property="SomeProp" Value="SomeValue"/>
</Style>
这例如抛出一个错误,表明动态资源与 BaseOn 样式结合使用是不可能的.我想知道怎么会有人这样做?谢谢
this e.g. throws an error indicating that the usage of dynamicresources in combination with BasedOn styles is not possible. i wonder how someone could do that? thanks
推荐答案
我认为主要原因是密封对象.如果您有样式层次结构:
I think the main reason is sealed objects. If you have a Style hierarchy:
Style A
/ \
Style A1 Style A2
这可能不是一个困难的场景.您使用动态资源引用 StyleA
,因此每当该资源发生变化时,Style A1
和 Style A2
应更改它们的 BasedOn代码>属性.但是,一旦在您的应用程序中使用了 Style,它就会成为一个密封对象.
Style A
变得不可变.
this might not be a difficult scenario. You refer to StyleA
using a dynamic resource, so whenever that resource changes, Style A1
and Style A2
should change their BasedOn
property. However, once a Style is being used in your application, it becomes a sealed object. Style A
becomes immutable.
您可以使用的一种解决方法是:
One workaround you can use is:
Style A
需要改变.- 创建一个新的 Style 对象,该对象将成为新的
Style A
资源. - 创建
Style A1
和Style A2
的新版本.您需要编写一个复制过程来复制所有Setters
、Resources
等.将BasedOn
设置为新版本的样式 A
. - 更新资源集合,以便在其中包含三种新样式.
Style A
needs to change.- Create a new Style object that is going to be the new
Style A
resource. - Create a new version of
Style A1
andStyle A2
. You'd need to write a copy procedure that makes copies of all theSetters
,Resources
, etc. Set theBasedOn
to the new version ofStyle A
. - Update the resources collection so that the three new styles are in there.
{DynamicResource StyleA1}
和 {DynamicResource StyleA2}
现在应该知道这些资源发生了变化(从第 4 步开始)并自动更新任何引用.
{DynamicResource StyleA1}
and {DynamicResource StyleA2}
should now pick up the fact that those resources changes (from step 4) and update any references automatically.
请注意,这是一个非常简单的场景.现实世界风格的层次结构可能更复杂,尤其是当它们分布在多个文件中并且来自合并的字典时.
Note that this is a very simple scenario. Real world style hierarchies can be more complex, especially if they are spread across multiple files and come from merged dictionaries.
希望我理解您的问题并提供帮助.
Hope I understood your problem and helped out.
这篇关于在 DynamicResource 上使用 BasedOn 样式属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!