代码之家  ›  专栏  ›  技术社区  ›  Gergely Orosz

如何在Silverlight中合并样式?

  •  4
  • Gergely Orosz  · 技术社区  · 15 年前

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

    <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中动态合并样式。有人能证实这一点,或者给我展示一种更好的实现合并的方法吗?

    2 回复  |  直到 15 年前
        1
  •  8
  •   Ana Betts    15 年前

    “basedon”在Silverlight中工作吗?//WPF开发人员,永远不确定

        2
  •  2
  •   AnthonyWJones    15 年前

    你可以这样做:

    <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解析器上。

    推荐文章