Skip to main content
 首页 » 编程设计

c#之从 RadioGroup 中捕获选定的 RadioButton

2024年02月05日24lori

我有一个 radiobutton 组,它有两个 radiobuttons,如下所示。我可以看到他们两个。我在以下示例代码中使用了相同的方法 https://github.com/MvvmCross/MvvmCross-Tutorials/blob/master/ApiExamples/ApiExamples.Core/ViewModels/ViewModels.cs

当我调试代码以查看选择了哪个单选按钮时,我在 SelectedItem 中放置了一个调试点,但是当我更改单选按钮时,它既没有命中 set 也没有命中 选定项。如何捕获选择了哪个 radiobutton

ViewModel.axml

<MvxRadioGroup 
   android:layout_width="fill_parent" 
   android:layout_height="wrap_content" 
   android:orientation="horizontal" 
   android:textSize="40dp" 
   local:MvxItemTemplate="@layout/item_radio" 
   local:MvxBind="ItemsSource Items;SelectedItem SelectedItem" /> 

Item_Radio.axml

<?xml version="1.0" encoding="utf-8"?> 
<RadioButton xmlns:android="http://schemas.android.com/apk/res/android" 
  xmlns:local="http://schemas.android.com/apk/res-auto" 
  android:layout_width="fill_parent" 
  android:layout_height="wrap_content" 
  android:buttonTint="@color/primary" 
  local:MvxBind="Text Caption" /> 

ViewModel.cs

private List<Thing> _items = new List<Thing>() 
{     
   new Thing("Open"), 
   new Thing("Close"), 
 }; 
public List<Thing> Items 
{ 
   get { return _items; } 
   set { _items = value; RaisePropertyChanged(() => Items); } 
} 
private Thing _selectedItem = new Thing("Open"); 
public Thing SelectedItem 
{ 
  get { return _selectedItem; } 
  set { _selectedItem = value; RaisePropertyChanged(() => SelectedItem); } 
 } 

Thing.cs

public class Thing 
{ 
  public Thing(string caption) 
  { 
     Caption = caption; 
  } 
 
  public string Caption { get; private set; } 
 
  public override string ToString() 
  { 
    return Caption; 
  } 
 
  public override bool Equals(object obj) 
  { 
     var rhs = obj as Thing; 
     if (rhs == null) 
          return false; 
      return rhs.Caption == Caption; 
 } 
 
  public override int GetHashCode() 
  { 
    if (Caption == null) 
      return 0; 
    return Caption.GetHashCode(); 
  } 
} 

请您参考如下方法:

如果您在输出窗口中收到 MvxBind 警告:

MvxBind:Warning: Failed to create target binding for binding SelectedItem for SelectedItem

您有两种解决方案:

选项 1:

Mvvmcross 更新至 4.1.6 版。此版本将为您自动注册 MvxAppCompatSetupHelper.FillTargetFactories。

选项 2:

在您的 setup.cs 中,您需要手动注册 MvxAppCompatSetupHelper.FillTargetFactories:

protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry) 
{ 
    MvxAppCompatSetupHelper.FillTargetFactories(registry); 
    base.FillTargetFactories(registry); 
}