在.NET MAUI应用开发中,我们常常需要在集合列表中让用户选择其中一项,比如选择收货地址、切换账户类型等。CollectionView本身提供了选择功能,但如果想要更自由的单选样式,用RadioButton配合数据绑定是更直观的做法。下面介绍具体实现方式。

一、准备数据模型
首先定义一个简单的模型类,里面包含一个标识是否选中的布尔属性,以及展示用的文本。这样每一个列表项都能独立记录自己的选中状态。
public class ItemModel
{
public string Name { get; set; }
public bool IsSelected { get; set; }
}
二、构建ViewModel
在ViewModel中准备一个集合,并提供一个当前选中项的属性方便业务逻辑使用。
using System.Collections.ObjectModel;
public class MainViewModel
{
public ObservableCollection<ItemModel> Items { get; set; }
public MainViewModel()
{
Items = new ObservableCollection<ItemModel>
{
new ItemModel { Name = "选项一", IsSelected = false },
new ItemModel { Name = "选项二", IsSelected = true },
new ItemModel { Name = "选项三", IsSelected = false }
};
}
}
三、XAML页面布局
在页面里使用CollectionView,将其SelectionMode设为None,然后在DataTemplate中放一个RadioButton,把IsChecked绑定到模型的IsSelected,GroupName设成一样就能实现互斥单选。
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="DemoApp.MainPage">
<VerticalStackLayout Padding="20">
<CollectionView ItemsSource="{Binding Items}" SelectionMode="None">
<CollectionView.ItemTemplate>
<DataTemplate>
<VerticalStackLayout>
<RadioButton Content="{Binding Name}"
IsChecked="{Binding IsSelected}"
GroupName="listGroup" />
</VerticalStackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</VerticalStackLayout>
</ContentPage>
四、绑定上下文
在后台代码中把ViewModel赋值给BindingContext,列表就能正常渲染并响应单选操作。
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
BindingContext = new MainViewModel();
}
}
五、获取选中项
由于RadioButton的选中状态已经双向绑定到IsSelected,你可以随时从Items里找到IsSelected为true的项,如下所示:
var selected = Items.FirstOrDefault(i => i.IsSelected);
if (selected != null)
{
// 使用选中的项
}
注意事项
- GroupName必须一致,否则RadioButton不会互斥。
- CollectionView的SelectionMode要设成None,避免和RadioButton逻辑冲突。
- 如果列表数据动态变化,使用ObservableCollection可自动通知界面更新。
通过上述方式,就能在MAUI中利用RadioButton轻松实现CollectionView的单选列表项,界面清晰且逻辑简单。
MAUIRadioButtonCollectionView修改时间:2026-07-29 07:15:18