Is there any way to combine mutliple styles in XAML to make a new style that has all of the desired settings?
For example (pseudo code);
<Style x:key="A">
...
</Style>
<Style x:key="B">
...
</Style>
<Style x:key="Combined">
<IncludeStyle Name="A"/>
<IncludeStyle Name="B"/>
... other properties.
</Style>
I know that there is a BasedOn property for styles, but that feature will only take you so far. I am really just looking for an easy way (in XAML) to create these ‘combined’ styles. But like I said before, I doubt it exists, unless anyone has heard of such a thing??
You can make a custom markup extensions that will merge styles properties and triggers into a single style. All you need to do is add a
MarkupExtension-derived class to your namespace with theMarkupExtensionReturnTypeattribute defined and you’re off and running.Here is an extension that will allow you to merge styles using a "css-like" syntax.
MultiStyleExtension.cs
Your example would then be solved by going:
We have defined a new style named "Combined" by merging two other styles "A" and "B" within the built-in
BasedOnattribute (used for style inheritance). We can optionally add other properties to the new "Combined" style as per usual.Other Examples:
Here, we define 4 button styles, and can use them in various combinations with little repetition:
You can even use the "
." syntax to merge the "current" default style for a type (context-dependent) with some additional styles:The above will merge the default style for
TargetType="{x:Type Button}"with the two supplemental styles.Credit
I found the original idea for the
MultiStyleExtensionat bea.stollnitz.com and modified it to support the "." notation to reference the current style.