从RadioGroup捕获选定的RadioButton

时间:2016-05-25 22:46:25

标签: c# xamarin xamarin.android mvvmcross

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

当我调试代码以查看选择了哪个单选按钮时,我在SelectedItem中放了一个调试点,但是当我更改单选按钮时,它既没有设置,也没有进入SelectedItem 。如何捕获选择的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();
  }
}

1 个答案:

答案 0 :(得分:4)

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

  

MvxBind:警告:无法为绑定创建目标绑定   SelectedItem的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);
}