我的目标是扩展一个对象已经设置的样式。假设我有以下两种样式:
<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中没有动态合并样式的方法。有人能否确认这一点或向我展示更好的方法来实现合并?