我的目标是扩展已设置的对象样式。假设我有以下两种风格:
<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分配给Ellipse,然后应用第二种样式,只更改它影响的属性。理想情况下,我想做这样的事情:
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!
我试图动态构造一个新的Style并添加NewStyle和OldStyle的属性 - 但是样式的Property属性总是为null,所以这导致死胡同:
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中动态合并样式。有人可以证实这一点,或者向我展示一种更好的方法来实现合并吗?
答案 0 :(得分:8)
“BasedOn”在Silverlight中有效吗? // wpf开发者,永远不会确定
答案 1 :(得分: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解析器尚未处理的内容。