我的目标是扩展对象已经设置的样式。所以假设我有以下两种风格:
<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的属性-但是样式的属性始终为空,因此这会导致死胡同:
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中动态合并样式。有人能证实这一点,或者给我展示一种更好的实现合并的方法吗?