我正在使用 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>
如何创建这样一组按钮?