如何创建一组行为类似RadioButtons的ToggleButtons?

Sör*_*ren 14 wpf xaml listbox radio-button togglebutton

我正在使用C#和WPF,我基本上想要一些切换按钮,并且只能同时选择其中一个.

我发现了另一个问题,但是那里显示的解决方案不起作用,我不知道为什么.

如果我尝试做在上面的问题中提到的ItemTemplateListBox不适用.我只是没有将切换按钮放入列表框,而是显示为"正常列表框".

我的切换按钮样式如下所示,包含在我的一个资源文件中:

<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>
Run Code Online (Sandbox Code Playgroud)

我想直接在XAML代码中添加项目,所以我的代码看起来像

<ListBox Style="{StaticResource ToggleButtonListBox}">
    <ListBoxItem>test1</ListBoxItem>
    <ListBoxItem>test2</ListBoxItem>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

如何创建这样一组按钮?

R. *_*des 37

如果你想要看起来像切换按钮的单选按钮,那么样式的单选按钮看起来不像是切换按钮可以解决你的问题吗?

<StackPanel>
    <RadioButton GroupName="groupFoo" Style="{StaticResource {x:Type ToggleButton}}">Button 1</RadioButton>
    <RadioButton GroupName="groupFoo" Style="{StaticResource {x:Type ToggleButton}}">Button 2</RadioButton>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

  • 问题是你不能取消选中 (6认同)