ToggleButtuons ItemsControl 一次只会检查一个

ToggleButtuons ItemsControl only one will be Checked at a time

我有这个 ItemsControl,每个项目都是 ToggleButton

public List<string> MyList { get; set; } = new() {"A", "B", "C", "D"};

<ItemsControl ItemsSource="{Binding MyList}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <ToggleButton Content="{Binding}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

怎么可能一次只检查一项?

我想避免这种情况

您可以使用带有在其 ControlTemplate 中声明 ToggleButton 的 ListBoxItem 样式的 ListBox,而不是 ItemsControl。

将 ToggleButton 的 IsChecked 属性 绑定到 ListBoxItem 的 IsSelected 属性。 ListBox 的默认 SelectionModeSingle,因此只会选择并检查一项。

请注意,您不能使用 TemplateBinding,因为它本质上是 one-way。

<ListBox ItemsSource="{Binding MyList}">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <ToggleButton
                            Content="{Binding}"
                            IsChecked="{Binding IsSelected,
                                RelativeSource={RelativeSource TemplatedParent}}"/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

另一种可能是共享 GroupName 的 RadioButton。您必须将它们设置为看起来像 ToggleButtons。

<ItemsControl ItemsSource="{Binding MyList}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <RadioButton
                Style="{StaticResource ResourceKey={x:Type ToggleButton}}"
                Content="{Binding}"
                GroupName="Buttons"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>