【问题标题】:How can styles be merged in Silverlight?如何在 Silverlight 中合并样式?
【发布时间】:2010-01-15 17:07:29
【问题描述】:

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

<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 属性始终为空,所以这会导致死胡同:

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 中动态合并样式。有人可以确认这一点或向我展示实现合并的更好方法吗?

【问题讨论】:

    标签: silverlight silverlight-3.0 styles


    【解决方案1】:

    “BasedOn”在 Silverlight 中有效吗? // wpf 开发者,不确定

    【讨论】:

      【解决方案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 解析器尚未处理的内容。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-18
        • 2017-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多