Trigger doesn't work on ToggleButton.IsChecked

2019-02-19 09:23发布

问题:

Here is a simple XAML with trigger that should change ToggleButton content when it is checked. But for some reason it doesn't work. I have a silly feeling that I missed something extra small. Appreciate your help

<ToggleButton Content="&lt;">
    <ToggleButton.Style>
        <Style TargetType="ToggleButton">
            <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter Property="Content" Value="&gt;" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ToggleButton.Style>
</ToggleButton>

回答1:

You must move Content="&lt;" from ToggleButton to setter of Style.

Example:

<ToggleButton>
    <ToggleButton.Style>
        <Style TargetType="ToggleButton">
            <Setter Property="Content" Value="&lt;" />

            <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter Property="Content" Value="&gt;" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ToggleButton.Style>
</ToggleButton>

Because local value has higher precedence order over Style setters and triggers:

  1. Property system coercion.

  2. Active animations, or animations with a Hold behavior.

    3. Local value.

  3. TemplatedParent template properties.

  4. Implicit style.

    6. Style triggers.

  5. Template triggers.

    8. Style setters.

...

For more information, please see:

MSDN: Dependency Property Value Precedence



回答2:

You are overriding the Content set by the Trigger by setting the Content attribute at the control level. You want to set it using a Setter within the Style instead:

<ToggleButton>
    <ToggleButton.Style>
        <Style TargetType="ToggleButton">
         <Setter Property="Content" Value="&lt;" />
            <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter Property="Content" Value="&gt;" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ToggleButton.Style>
</ToggleButton>