【问题标题】:How can I create a set of ToggleButtons that behave like RadioButtons?如何创建一组行为类似于 RadioButtons 的 ToggleButtons?
【发布时间】:2011-06-23 12:25:49
【问题描述】:

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

我找到了another question,但那里显示的解决方案不起作用,我不知道为什么。

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

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

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

如何创建这样一组按钮?

【问题讨论】:

标签: wpf xaml listbox radio-button togglebutton


【解决方案1】:

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

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

【讨论】:

  • 是的,我认为这实际上解决了我的问题。这比我尝试做的要容易得多。即使我想了一会儿,我也无法想象它工作得那么好,那么容易。我会将解决方案编辑到上面的问题中。非常感谢!
  • @Sören:这是 WPF 最伟大的事情之一:行为与表示是分开的。此外,最好将解决方案作为答案发布。一段时间后,您可以接受它作为正确答案。
  • 我知道,我试图接受它,但它还没有工作(3 分钟锁定)。现在它做到了。再次感谢!
  • 问题是你不能取消勾选
  • 不幸的是“x:Type ToggleButton”技巧不再起作用 - 我有 VS 15.7.4 和 .NET 4.7.2 并且 VS 抱怨“资源“{x:Type ToggleButton}”不能解决”!呵呵……
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-26
  • 2012-04-08
  • 2015-04-16
  • 1970-01-01
  • 2011-05-31
  • 2013-03-04
相关资源
最近更新 更多