Change a style dynamically in WPF

Viewed 40850

Is there a way to change(and apply) a style dynamically in WPF?

Say I have the style declared in 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. In a moment, I need to change the Pink color, to, say Green, and all lines with style MyLineStyleKey became Green. A line is Pink when released, and Blue when selected... Now, I needed to change the unselected property(Pink to Green)..., so this is not just setting it to an other color, the trigger (selection>Blue) will not work anymore...Is that possible? How?

  2. Is that possible to bind to the Pink color in the Style, say, to a Button background, that will reflect the currently used style color?

EDIT:
For 1 I tried:

Style s = (Style)this.Resources["MyLineStyleKey"];

(s.Setters[0] as Setter).Value = background;
(s.Setters[1] as Setter).Value = background;

but an exception occured:

After a 'SetterBase' is in use (sealed), it cannot be modified.

2 Answers
Related