如何在Silverlight中合并样式?

4

我的目标是扩展一个对象已经设置的样式。假设我有以下两种样式:

<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>

我想要做的是将OriginalStyle分配给椭圆形,然后稍后只更改它所影响的属性应用第二个样式。因此,理想情况下,我想要做的是像这样做:
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!

我曾尝试动态构建一个新样式,并添加NewStyle和OldStyle的属性,但是样式的Property属性始终为空,这导致了失败:

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."
}

似乎在Silverlight中没有动态合并样式的方法。有人能否确认这一点或向我展示更好的方法来实现合并?

2个回答

8
"BasedOn" 在 Silverlight 中是否可用?// WPF 开发者,从未确定

2
您可以简单地这样做:-
<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>

请注意,这种Style元素的出现顺序很重要,您不能将样式基于尚未被XAML解析器处理的内容。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接