How can I create a set of ToggleButtons that behave like RadioButtons?

Sören picture Sören · Feb 8, 2011 · Viewed 15k times · Source

I am using C# and WPF and I basically want to have some toggle buttons and only one of them can be selected at the same time.

I found another question about that, but the solution shown there does not work and I don't know why.

If I try to do it as mentioned in the question above, the ItemTemplate of the ListBox is not applied. I just don't get the toggle buttons into the listbox, instead it is shown as a "normal listbox".

My toggle button style looks like this, contained in one of my resource files:

<Style x:Key="ToggleButtonListBox" TargetType="{x:Type ListBox}">
    <Setter Property="ListBox.ItemTemplate">
        <Setter.Value>
            <DataTemplate>
                <ToggleButton Content="{Binding}"
                          IsChecked="{Binding IsSelected, Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}" />
            </DataTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="ListBox.ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="BorderThickness" Value="0" />
</Style>

I would like to add the items directly in the XAML code, so my code for that would look something like

<ListBox Style="{StaticResource ToggleButtonListBox}">
    <ListBoxItem>test1</ListBoxItem>
    <ListBoxItem>test2</ListBoxItem>
</ListBox>

How can I create such a set of buttons?

Answer

R. Martinho Fernandes picture R. Martinho Fernandes · Feb 8, 2011

If you want radio buttons that look like toggle buttons won't radio buttons styled to look like toggle buttons solve your problem?

<StackPanel>
    <RadioButton GroupName="groupFoo" Style="{StaticResource {x:Type ToggleButton}}">Button 1</RadioButton>
    <RadioButton GroupName="groupFoo" Style="{StaticResource {x:Type ToggleButton}}">Button 2</RadioButton>
</StackPanel>