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

Xamarin MVVM中如何获取Syncfusion SfRadioButton的选中值

解决方案

你的问题核心是未对SfRadioGroup配置选中值的双向绑定,因此单选按钮的选中状态变化无法同步回ViewModel,按照以下步骤修改即可正常获取选中值:

方案1:绑定选中对象(推荐)

可以直接获取完整的选中支付方式对象,方便后续业务逻辑调用

修改XAML代码

为SfRadioGroup添加SelectedItem双向绑定:

<syncfusion:SfRadioGroup x:Name="radioGroup"
      BindableLayout.ItemsSource="{Binding Items}"
      SelectedItem="{Binding SelectedPaymentMethod, Mode=TwoWay}">
    <BindableLayout.ItemTemplate>
        <DataTemplate>
            <syncfusion:SfRadioButton Text="{Binding PaymentMethod}" />
        </DataTemplate>
    </BindableLayout.ItemTemplate>
</syncfusion:SfRadioGroup>

修改ViewModel代码

新增选中项属性,可同步返回你需要的选中id:

// 原有列表属性保留
public List<PaymentMthd> Items { get; set; }

// 新增选中支付方式属性
private PaymentMthd _selectedPaymentMethod;
public PaymentMthd SelectedPaymentMethod
{
    get => _selectedPaymentMethod;
    set 
    { 
        SetProperty(ref _selectedPaymentMethod, value);
        // 选中项变化时自动同步id到原有IsChecked属性
        if(value != null)
        {
            IsChecked = value.id;
            // 可直接在此处添加选中变化后的业务逻辑
        }
    }
}

// 原有id属性保留
private int _IsChecked;
public int IsChecked
{
    get => _IsChecked;
    set => SetProperty(ref _IsChecked, value);
}

// 构造函数内的列表初始化代码保留
Items = new List<PaymentMthd>()
{
    new PaymentMthd(){PaymentMethod = "Cash" , id = 1},
    new PaymentMthd(){PaymentMethod = "Visa Card" , id = 2},
};

方案2:仅绑定选中id

如果不需要完整的选中对象,也可以直接绑定SfRadioGroup的SelectedIndex,配合值转换器将索引转换为对应支付方式的id即可适配你现有的IsChecked属性,无需额外新增属性。

注意事项

  • 绑定必须添加Mode=TwoWay,否则选中状态变化不会回传到ViewModel
  • 如果列表需要动态更新,建议将List<PaymentMthd>替换为ObservableCollection<PaymentMthd>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:09:02