代码之家  ›  专栏  ›  技术社区  ›  serhio

在WPF中动态更改样式

  •  18
  • serhio  · 技术社区  · 14 年前

    假设我在XAML中声明了样式:

        <Style TargetType="local:MyLine" 
               x:Key="MyLineStyleKey" x:Name="MyLineStyleName">
            <Setter Property="Fill" Value="Pink"/>
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="true">
                    <Setter Property="Fill" Value="Blue" />                    
                </Trigger>
            </Style.Triggers>
        </Style>
    
    1. 改变 这个 Pink 颜色,比如说 Green MyLineStyleKey 变成绿色。释放时线条为粉红色,选中时为蓝色。。。现在,我需要更改未选中的属性(从粉红色改为绿色)…因此,这不仅仅是将其设置为其他颜色,触发器(选择蓝色)将不再工作…这可能吗?怎么用?

    2. 有可能吗 对于样式中的粉色,比如说按钮背景,那会反映当前使用的样式颜色吗?

    编辑:
    我试过:

    Style s = (Style)this.Resources["MyLineStyleKey"];
    
    (s.Setters[0] as Setter).Value = background;
    (s.Setters[1] as Setter).Value = background;
    

    但出现了一个例外:

    在使用“SetterBase”之后 (sealed),不可修改。

    2 回复  |  直到 13 年前
        1
  •  26
  •   Isak Savo    14 年前

    创建画笔作为资源

    <SolidColorBrush x:Key="MyFillBrush" Color="Pink" />
    

    以你的风格引用

    <Style x:Key="MyShapeStyle" TargetType="Shape">
        <Setter Property="Fill" Value="{DynamicResource MyFillBrush}" />
    </Style>
    ...
    <!-- Then further down you may use it like this -->
    <StackPanel Width="100">
        <Rectangle Style="{StaticResource MyShapeStyle}" Height="50" Margin="8" />
        <Rectangle Style="{StaticResource MyShapeStyle}" Height="50" Margin="8" />
        <Ellipse Style="{StaticResource MyShapeStyle}" Height="50" Margin="8" />
        <Button Content="Click to change color" Click="Button_Click" Margin="8" />
    </StackPanel>
    

    现在要更改使用“MyShapeStyle”样式的所有形状的颜色,可以从代码隐藏中执行以下操作:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Random r = new Random();
        this.Resources["MyFillBrush"] = new SolidColorBrush(Color.FromArgb(
              0xFF, 
              (byte)r.Next(255), 
              (byte)r.Next(255), 
              (byte)r.Next(255)));
    }
    

    使这项工作成功的原因是你使用了 DynamicResource 对于样式中的笔刷引用,这将告诉WPF监视该资源以进行更改。如果你使用 StaticResource 相反,你不会得到这种行为。

        2
  •  20
  •   Thomas Levesque    14 年前

    样式只能在首次使用前修改。来自MSDN:

    当另一个样式基于某个样式或第一次应用该样式时,该样式将被密封。

    Style newStyle = new Style();
    newStyle.BasedOn = originalStyle;
    newStyle.TargetType = typeof(MyLine);
    Brush blue = new SolidColorBrush(Colors.Blue);
    newStyle.Setters.Add(new Setter(Shape.FillProperty, blue));
    newStyle.Setters.Add(new Setter(Shape.StrokeProperty, blue));