Capture selected RadioButton from the RadioGroup

2019-07-25 17:15发布

I have radiobutton group, which has two radiobuttons as follows. I could able to see both of them. I have used the same approach from the following sample code https://github.com/MvvmCross/MvvmCross-Tutorials/blob/master/ApiExamples/ApiExamples.Core/ViewModels/ViewModels.cs

When I debug the code in order to see which radio button is selected, I put a debug point in the SelectedItem but when I change radio button it does hit neither set or get in the SelectedItem. How do I capture which radiobutton is selected

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条回答
女痞
2楼-- · 2019-07-25 17:47

If you are getting an MvxBind Warning in your output window:

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

You have two options to resolve:

Option 1:

Update to version 4.1.6 of Mvvmcross. This version will automatically register MvxAppCompatSetupHelper.FillTargetFactories for you.

Option 2:

In you setup.cs you need to register MvxAppCompatSetupHelper.FillTargetFactories manually:

protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
{
    MvxAppCompatSetupHelper.FillTargetFactories(registry);
    base.FillTargetFactories(registry);
}
查看更多
登录 后发表回答