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>
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
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
needs to change. Style A
resource.Style A1
and Style A2
. You'd need to write a copy procedure that makes copies of all the Setters
, Resources
, etc. Set the BasedOn
to the new version of Style A
.{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.
I've found that since you can't use BasedOn
on a DynamicResource
, you can "convert" the DynamicResource
to StaticResource
by merging the ResourceDictionary
holding your "parent" resources to your current Window/UserControl/whatever. This way you are now able to refer to the resource object (eg. Style
) using StaticResource
. This way you can use Datatriggers
on DynamicResource
(through conversion).
Example:
<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>
Hence Datatriggers
are applied to a button styled in an imported ResourceDictionary
.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With