我的目标是扩展已经设置好的对象样式。所以假设我有以下两种风格:
<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中动态合并样式。谁能证实这一点,或者向我展示一种更好的实现合并的方法?
发布于 2010-01-16 01:09:41
"BasedOn“能在Silverlight中工作吗? // wpf developer,永远不确定
发布于 2010-01-16 18:13:53
你可以简单地这样做:
<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解析器尚未处理的内容上。
https://stackoverflow.com/questions/2073393
复制相似问题