Question

I've declared the below style. How can I override the style foreground color dynamically in my vb.net?

<Style x:Key="LabelWinner" TargetType="{x:Type Label}">
        <Setter Property="Effect">
            <Setter.Value>
                <DropShadowEffect Color="#FF000000" ShadowDepth="6" />
            </Setter.Value>
        </Setter>
        <Setter Property="Foreground" Value="#FFFF0000"/>
    </Style>
Was it helpful?

Solution

As mentioned in the comment @nit, In WPF have a powerful system behavior properties in the form of Style.Triggers.

Earlier, in WinForms to change a specific property, we had to do it through the code that was not quite comfortable and practical. The developers of WPF decided to separate the visual logic related to the appearance of the program, and business logic, which contains the desired behavior of the program. Actually, it was a Style.

To set the Style trigger, you need to select the appropriate properties. The trigger is as follows:

<Trigger Property="SomeProperty" Value="SomeValue">

... Some actions by way of setters...

</Trigger>

For example, we want to see, when you hover the mouse cursor changes Foreground color and FontSize. Then we choose the property IsMouseOver, and then write a Trigger:

<Style x:Key="LabelWinner" TargetType="{x:Type Label}">
    <Setter Property="Effect">
        <Setter.Value>
            <DropShadowEffect Color="#FF000000" ShadowDepth="6" />
        </Setter.Value>
    </Setter>

    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Foreground" Value="Green" />
            <Setter Property="FontSize" Value="14" />
        </Trigger>
    </Style.Triggers>
</Style>

It should be remembered, that in WPF have a list of value precedence (MSDN), that the local value of a higher priority than the trigger style. Therefore, if you value for property of Label will be set locally, the trigger will not be able to change it, for example:

<Label Foreground="Red" ... /> <!-- Trigger don't change foreground -->

If the standard property are missing, or the need to implement your scenario, then it have the attached dependency property (MSDN). Inside it, you can set any condition, for example to start the animation and the trigger in the style it will work.

Example of trigger with attached dependency property:

<Trigger Property="local:YourClass.MyProperty" Value="True">
    <Setter TargetName="SaveButton" Property="Background" Value="AliceBlue" />
</Trigger>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top