wpf - 如何使用 ObservableCollection 源实现 XAML 单选按钮控件?

标签 wpf xaml combobox radio-button

我在 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/

相关文章:

c# - 如何在标准 WPF ListView 中启用 UI 虚拟化

c# - 在 Xamarin.Forms 中使用 xaml 以大写形式显示标签文本

C# WPF 组合框选择第一项

c# 组合框绑定(bind)到对象列表

c# - 格式化组合框的文本,C#

c# - WPF 使用相对路径从程序集中的任何位置访问资源

c# - 在 WPF 中显示 "Wait"屏幕

c# - 我如何使代码等到 bool 信号继续

WPF - 在代码中访问 XAML 资源

c# - 在新的 Xamarin.Forms 项目中抛出“System.Exception”