15

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

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

如果我尝试按照上述问题中所述ItemTemplate进行操作,ListBox则不适用。我只是没有将切换按钮放入列表框中,而是显示为“普通列表框”。

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

<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>

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

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

如何创建这样一组按钮?

4

1 回答 1

39

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

<StackPanel>
    <RadioButton GroupName="groupFoo" Style="{StaticResource {x:Type ToggleButton}}">Button 1</RadioButton>
    <RadioButton GroupName="groupFoo" Style="{StaticResource {x:Type ToggleButton}}">Button 2</RadioButton>
</StackPanel>
于 2011-02-08T15:19:14.673 回答