Adrian Kole

Adrian Kole

  • NA
  • 1
  • 4.6k

WPF DataTrigger bound ToggleButton not getting checked

Mar 7 2014 6:56 PM

I'm trying to accomplish having a couple of ToggleButtons act sort of like radio buttons--but with the important difference being that having neither checked is a valid case (only up to one can be checked at a time, they are mutually-exclusive).

Here is some XAML that almost works:

<Window>
    <Grid>
        <ToolBarTray DockPanel.Dock="Top">
            <ToolBar>
                <ToggleButton x:Name="ShowLineGridToggleButton">
                    <ToggleButton.Style>
                        <Style TargetType="ToggleButton">
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding IsChecked, ElementName=ShowDotGridToggleButton}" Value="True">
                                    <Setter Property="IsChecked" Value="False" />
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </ToggleButton.Style>
                    <Image Source="../Images/ShowLineGrid.png" />
                </ToggleButton>
                <ToggleButton x:Name="ShowDotGridToggleButton">
                    <ToggleButton.Style>
                        <Style TargetType="ToggleButton">
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding IsChecked, ElementName=ShowLineGridToggleButton}" Value="True">
                                    <Setter Property="IsChecked" Value="False" />
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </ToggleButton.Style>
                    <Image Source="../Images/ShowDotGrid.png" />
                </ToggleButton>
            </ToolBar>
        </ToolBarTray>
    <Grid>
</Window>

Clicking on one button will indeed uncheck the other. Unfortunately what is also happening is that the button clicked does not get checked. The background changes properly when the mouse is moved over it, but when the mouse moves away the button shows as not selected.

Commenting-out the Setters allows the clicked button to be checked. It's as if the Setter is also unchecking the clicked button.

I would rather handle this in XAML than have to resort to implementing in code via event handlers; this would keep everything defined in one place.

Ideas?

TIA!


Answers (1)