我在 XAML 中有以下 ComboBox 元素:
<ComboBox ItemsSource="{Binding CollectionControlValues}"
SelectedItem="{Binding CollectionControlSelectedValue, UpdateSourceTrigger=PropertyChanged}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Value}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
我想以相同的方式实现RadioButtons,如下所示:
伪代码:
<RadioButtons ItemsSource="{Binding CollectionControlValues}"
SelectedItem="{Binding CollectionControlSelectedValue, UpdateSourceTrigger=PropertyChanged}">
<RadioButtons .ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Value}" />
</DataTemplate>
</RadioButtons .ItemTemplate>
</RadioButtons >
但是,我能找到的唯一 WPF RadioButton 实现是这样的静态。
<StackPanel x:Name="rbHolder1" Style="{StaticResource rbStackPanelStyle}">
<RadioButton Style="{StaticResource rbStyle}">RadioButton 1</RadioButton>
<RadioButton Style="{StaticResource rbStyle}">RadioButton 2</RadioButton>
<RadioButton Style="{StaticResource rbStyle}">RadioButton 3</RadioButton>
<RadioButton Style="{StaticResource rbStyle}">...</RadioButton>
</StackPanel>
如何创建一个 RadioButton 控件,该控件不像上面那样是静态的,而是从其 ItemsSource 属性获取数据,如上面的 ComboBox 示例中所示?
最佳答案
使用 ItemsControl 和 DataTemplate:
<ItemsControl ItemsSource="{Binding CollectionControlValues}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton Content="{Binding Value}" IsChecked="{Binding SomeProperty}" GroupName="name"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
关于wpf - 如何使用 ObservableCollection 源实现 XAML 单选按钮控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1425968/