我正在关注this answer on how to databind enums (ints in my case) to RadioButtons,但如果我有几个TabItem,每个都有10x10的RadioButtons网格,有没有办法摆脱一些样板?因此,每个RadioButton都必须包含所有这些信息:
<RadioButton
IsChecked="{Binding
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}},
Path=FavoriteColor,
Converter={StaticResource IntToBoolConverter},
Mode=TwoWay,
ConverterParameter=5}"
Content="Red" Grid.Column="4" Grid.Row="6" />
我希望能够在TabControl中设置一次RelativeSource,转换器和模式,在每个TabItem中设置一次Path,并且每个RadioButton只设置ConverterParameter。这在XAML中是否可行?如果没有,那么在代码隐藏中做这件事会更有意义吗?
答案 0 :(得分:8)
使用ListBoxes
的单一选择模式,对my answer on a related question进行了改进:
<ListBox SelectionMode="Single" SelectedItem="{Binding EnumValue}"
Style="{StaticResource BorderlessStyle}">
<ListBox.Resources>
<ObjectDataProvider x:Key="items" MethodName="GetValues"
ObjectType="{x:Type sys:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:MainWindow+TestEnum" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</ListBox.Resources>
<ListBox.ItemsSource>
<Binding Source="{StaticResource items}" />
</ListBox.ItemsSource>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<!-- Automatic grid layout, adjust as needed -->
<UniformGrid Columns="2" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<RadioButton Content="{Binding}"
IsChecked="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ListBoxItem}}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
使ListBox
本身消失的风格:
<Style x:Key="BorderlessStyle" TargetType="ListBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBox">
<ItemsPresenter />
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<ContentPresenter />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
</Style>