MAUI RadioButton怎么用 MAUI单选按钮使用教程

admin 百科 15
MAUI中RadioButton靠GroupName属性显式分组实现互斥,必须设相同非空字符串值;通过RadioButtonGroup.SelectedValue绑定Value属性管理选中状态,初始选中由SelectedValue匹配Value决定,CheckedChanged事件仅响应用户点击。

MAUI RadioButton怎么用 MAUI单选按钮使用教程-第1张图片-佛山资讯网

MAUI 中的 RadioButton 不像传统平台那样依赖容器分组(如 Android 的 RadioGroup 或 Qt 的父控件自动互斥),而是靠 GroupName 属性显式定义逻辑分组,同一组内自动互斥——这是最核心的使用前提。

分组必须用 GroupName

多个 RadioButton 要实现单选,必须给它们设置相同的 GroupName 值。这个值是字符串,区分大小写,且不能为空。没有 GroupName 的 RadioButton 是独立的,不参与任何互斥逻辑。

  • 推荐在 XAML 中统一写在父布局上,用附加属性方式批量设置:RadioButtonGroup.GroupName="gender"
  • 每个 RadioButton 自己也支持 GroupName="gender",但分散写容易遗漏或不一致
  • 不同组可用不同名称,比如 "gender""role",彼此完全隔离

获取和绑定选中值

MAUI 不直接暴露“哪个 RadioButton 被选中”,而是通过 RadioButtonGroup.SelectedValue 统一管理。它会自动同步为当前被选中项的 Value 属性值(类型为 object,通常用 string)。

  • 在 ViewModel 中定义一个 string 类型属性(如 SelectedGender),并双向绑定到 RadioButtonGroup.SelectedValue
  • 每个 RadioButton 设置 Value="Male"Value="Female" 等,值要与绑定属性类型兼容
  • 用户点击后,SelectedGender 自动更新,无需手动监听事件

默认选中和初始状态

默认选中不是靠 IsChecked="True"(该属性在 MAUI RadioButton 中只读,设了也没用),而是靠 让 SelectedValue 初始值匹配某个 RadioButton 的 Value

标签: android edge

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~