You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin.Forms中能否通过容器ID获取单选按钮内容?

问题解答

1. 修正你的XAML代码

你当前的代码缺少容器的标识设置,需要给StackLayout添加x:Name(也就是你所说的容器ID),这样才能在后台代码中定位到该容器。修改后的代码如下:

<StackLayout x:Name="IDTypeContainer" RadioButtonGroup.GroupName="ID_type">
    <RadioButton Content="National ID"/>
    <RadioButton Content="Voters ID"/>
    <RadioButton Content="Drivers License"/>
    <RadioButton Content="PRC ID"/>
    <RadioButton Content="Postal ID"/>
    <RadioButton Content="Others:"/>
</StackLayout>

2. 后台代码获取选中的RadioButton内容

通过容器的Children集合遍历筛选,找到IsChecked为true的RadioButton,即可获取对应的Content:

// 筛选出选中的单选按钮
var selectedRadio = IDTypeContainer.Children.OfType<RadioButton>().FirstOrDefault(r => r.IsChecked);
if (selectedRadio != null)
{
    string selectedContent = selectedRadio.Content.ToString();
    // 此处可对选中内容做后续业务处理
}

3. 关键注意点

  • 你已经正确给所有RadioButton设置了统一的RadioButtonGroup.GroupName,这样它们会保持互斥选中的特性,无需额外调整。
  • 如果需要实时监听选中状态变化,可以给容器内的RadioButton统一绑定CheckedChanged事件,或者采用MVVM模式将IsChecked属性绑定到ViewModel中处理。

内容的提问来源于stack exchange,提问作者HelloFriend

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 13:20:50