我想知道是否有办法在动态资源中使用wpf样式的basedOn属性。例如:
<Style BasedOn="{DynamicResource somestyle}">
<Setter Property="SomeProp" Value="SomeValue"/>
</Style>例如,这会抛出一个错误,指示动态资源与BasedOn样式的结合使用是不可能的。我想知道怎么会有人这么做?谢谢
发布于 2009-02-25 14:37:06
我认为主要原因是密封的对象。如果您有样式层次结构:
Style A
/ \
Style A1 Style A2这可能不是一个困难的场景。您使用动态资源引用StyleA,因此每当该资源发生更改时,Style A1和Style A2都应该更改其BasedOn属性。但是,一旦在应用程序中使用了样式,它就会变成一个密封对象。Style A变得不可变。
您可以使用的一种解决方法是:
Style A需要改变。Style A1和Style A2的新版本的新Style A。您需要编写一个复制过程来复制所有的Setters、Resources等。将BasedOn设置为新版本的资源集合,这样三种新样式就会出现在其中。{DynamicResource StyleA1}和{DynamicResource StyleA2}现在应该会发现这些资源发生了变化(从步骤4开始),并自动更新任何引用。
请注意,这是一个非常简单的场景。现实世界风格的层次结构可能更复杂,特别是当它们分布在多个文件中并来自合并的字典时。
希望我能理解你的问题并帮助你解决问题。
发布于 2012-02-17 18:19:22
我发现既然你不能在DynamicResource上使用BasedOn,你可以通过将保存你的“父”资源的ResourceDictionary合并到你当前的窗口/用户控件/其他东西来“转换”DynamicResource到StaticResource。这样,您现在就能够引用资源对象(例如,Style)使用StaticResource。这样,您就可以在DynamicResource上使用Datatriggers (通过转换)。
示例:
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/MyProject.Styles;component/ButtonStyles.xaml"/>
</ResourceDictionary.MergedDictionaries>
[*Your other resources can be put here*]
</ResourceDictionary>
</Window.Resources>
...
<Button Command="{Binding MyCommandInViewModel, RelativeSource={RelativeSource AncestorType=Window}}">
<Button.Style>
<Style BasedOn="{StaticResource StyleFromButtonStyles}" TargetType="Button">
<Style.Triggers>
<DataTrigger Binding="{Binding SomeBool}" Value="True">
<Setter Property="Button.Content" Value="{StaticResource SomeImage}"/>
</DataTrigger>
<DataTrigger Binding="{Binding SomeBool}" Value="False">
<Setter Property="Button.Content" Value="{StaticResource SomeOtherImage}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>因此,将Datatriggers应用于在导入的ResourceDictionary中设置样式的按钮。
希望这能有所帮助!
https://stackoverflow.com/questions/585429
复制相似问题