gbishop3 gbishop3 - 2 months ago 34
Android Question

MvxSpinner selecteditem not updated on itemssource change

I am building a form that involves adding items from a list, but the list that is being shown to the user depends on the selection from another list. To do this I have two MvxSpinners each with a bound ItemsSource and SelectedItem.

<MvxSpinner
android:layout_width="300dp"
android:layout_height="50dp"
local:MvxBind="ItemsSource item_source_one; SelectedItem selected_item_one;"/>
<MvxSpinner
android:layout_width="300dp"
android:layout_height="50dp"
local:MvxBind="ItemsSource item_source_two; SelectedItem selected_item_two;"/>


When
selected_item_one
changes
item_source_two
changes to a new list. All of this works, except when
item_source_two
is changed
selected_item_two
remains the same as it was before the change. I would like for the
selected_item_two
to match what is visually shown when
item_source_two
changes.

Answer

The spinner binding isn't perfect in MvvmCross - in particular, the SelectedItem change must be sent after the ItemsSource change.

To work around this, you could signal a fake SelectedItem change after the ItemsSource - e.g. something like:

 RaisePropertyChanged(() => item_source_two);
 RaisePropertyChanged(() => selected_item_two);

If you wanted to fix this more fully, you could also consider overriding MvxSpinner - sadly you can't easily inherit because we missed virtual, but you do something like:

public class MySpinner : MvxSpinner
{
    public MySpinner(Context context, IAttributeSet attrs)
        : base(context, attrs)
    {
    }

    [MvxSetToNullAfterBinding]
    public new IEnumerable ItemsSource
    {
        get { return base.ItemsSource; }
        set 
        { 
            // TODO - work out what the current selection and store it in a local variable
            base.ItemsSource = value; 
            // TODO - reset the current selection here from the local variable
        }
    }
}

inheriting from https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross.Binding.Droid/Views/MvxSpinner.cs