Reputation: 6485
My goal is to extend the already set style of an object. So assuming I have the following two styles:
<Style TargetType="Ellipse" x:Key="OriginalStyle">
<Setter Property="Fill" Value="Blue"/>
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="200"/>
</Style>
<Style TargetType="Ellipse" x:Key="NewStyle">
<Setter Property="Fill" Value="Red"/>
</Style>
What I'd like to do is assign OriginalStyle to an Ellipse, then later apply the second style only changing the properties it affects. So ideally I want to do something like this:
Style OriginalStyle;
Style NewStyle;
Ellipse ellipse = new Ellipse();
ellipse .Style = OriginalStyle;
// Later in an event hanler
ellipse.Style = NewStyle; // I would want to keep the settings from the old style in here: in this example setting the style like this would make me lose the Width and Height properties!
I've tried to dynamically construct a new Style and add the properties of NewStyle and OldStyle - however the Property property of the styles are always null so this lead to a dead end:
Style combinedStyle = new Style();
foreach (Setter setter in Old.Setters)
{
combinedStyle.Setters.Add(setter); // Get exception "Element is already the child of another element."
}
foreach (Setter setter in NewStyle.Setters)
{
combinedStyle.Setters.Add(setter); // Get exception "Element is already the child of another element."
}
It seems like there is no way to dynamically merge styles in Silverlight. Could someone confirm this or show me a better approach to achieve merging?
Upvotes: 4
Views: 544
Reputation: 189457
You can do it simply like this:-
<Style TargetType="Ellipse" x:Key="OriginalStyle">
<Setter Property="Fill" Value="Blue"/>
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="200"/>
</Style>
<Style TargetType="Ellipse" x:Key="NewStyle" BasedOn="{StaticResource OriginalStyle}">
<Setter Property="Fill" Value="Red"/>
</Style>
Note that the order of appearance of such Style
elements is important, you can not base a style on something that the XAML parser has not yet processed.
Upvotes: 2
Reputation: 74654
Does "BasedOn" work in Silverlight? // wpf developer, never sure
Upvotes: 8