我有這個 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>
一次只檢查一個專案怎么可能?
我想避免這種情況

uj5u.com熱心網友回復:
您可以使用具有在其 ControlTemplate 中宣告 ToggleButton 的 ListBoxItem 樣式的 ListBox,而不是 ItemsControl。
IsChecked將 ToggleButton 的屬性系結到IsSelectedListBoxItem 的屬性。ListBox的默認SelectionMode值為Single,因此只會選擇并檢查一項。
請注意,您不能使用 TemplateBinding,因為它本質上是單向的。
<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. 您必須將它們設定為看起來像 ToggleButtons。
<ItemsControl ItemsSource="{Binding MyList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton
Style="{StaticResource ResourceKey={x:Type ToggleButton}}"
Content="{Binding}"
GroupName="Buttons"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/479904.html
標籤:wpf
