15

私はC#とWPFを使用していますが、基本的にいくつかのトグルボタンが必要で、同時に選択できるのは1つだけです。

それについて別の質問を見つけましたが、そこに示されている解決策は機能せず、理由がわかりません。

上記の質問にあるようにしようとすると、ItemTemplateListBoxが適用されません。トグルボタンをリストボックスに入れず、代わりに「通常のリストボックス」として表示します。

トグル ボタンのスタイルは次のようになり、リソース ファイルの 1 つに含まれています。

<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 に答える