在MvvmCross中以编程方式创建和绑定Android Spinners

12

我正在开发一个跨平台的应用程序,需要动态生成和绑定Spinner控件。我已经在iOS和Windows平台上做到了这一点,但是在Android平台上遇到了问题。如果我理解得正确,我必须向MvxSpinner构造函数传递一些参数 - 上下文和属性,但我不知道如何做到这一点以及应该传递什么。此外,我也不知道如何绑定ItemsSource和SelectedItem。我想应该创建一个新的绑定集(类似于iOS版本),但是我不知道如何在Android上实现。能否给我一些指引呢?

以下是我从Windows版本中提取的源代码:

private void InputColourAtlasChangedMessageHandler( InputColourAtlasChangedMessage message )
{
    ColourAtlas selected = message.SelectedColourAtlas;
    var vm = ViewModel as ColorMatchViewModel;

    List<ComboBox> newComboboxes = new List<ComboBox>();
    var currentCount = ColourPickersContainer.Children.Count;
    for ( int i = currentCount; i < message.ColourCodePartCount; i++ )
    {
        ComboBox cb = new ComboBox { Margin = new Thickness( 0, 0, 10, 0 ), PlaceholderText = "choose" };
        Binding itemsSourceBinding = new Binding();
        itemsSourceBinding.Path = new PropertyPath( "ColourPartLists[" + i + "]" );
        Binding selectedItemBinding = new Binding();
        selectedItemBinding.Path = new PropertyPath( "SelectedColourCodeParts[" + i + "]" );
        selectedItemBinding.Mode = BindingMode.TwoWay;
        cb.Tag = i;
        ColourPickersContainer.Children.Add( cb );
        cb.SetBinding( ComboBox.ItemsSourceProperty, itemsSourceBinding );
        cb.SetBinding( ComboBox.SelectedItemProperty, selectedItemBinding );
        cb.SelectionChanged += cb_SelectionChanged;                                
        BindingOperations.SetBinding( cb, ComboBox.SelectedItemProperty, selectedItemBinding );
        newComboboxes.Add( cb );
    }
    while ( ColourPickersContainer.Children.Count > message.ColourCodePartCount )
    {
        ColourPickersContainer.Children.RemoveAt( ColourPickersContainer.Children.Count - 1 );
    }
    _comboboxes = newComboboxes;            
}

void cb_SelectionChanged( object sender, SelectionChangedEventArgs e )
{
    var cb = sender as ComboBox;
    int changedIndex = ( int )cb.Tag;
    if ( e.AddedItems.Count > 0 )
    {
        ( DataContext as ColorMatchViewModel ).ColourCodePartChangedCommand.Execute( changedIndex );
    }
}

这里是iOS版本(执行的操作基本相同,尽管它只是清除现有的旋转器而不是重用它们):

private void InputColourAtlasChangedMessageHandler( InputColourAtlasChangedMessage message )
{
    ColourAtlas selected = message.SelectedColourAtlas;
    ClearPickers();
    var currentSet = this.CreateBindingSet<ColorMatchView, ColorMatchViewModel>();
    for ( int i = 0; i < message.ColourCodePartCount; i++ )
    {
        var j = i;
        UIPickerView picker = new UIPickerView();
        var pickerViewModel = new MvxPickerViewModel( picker );
        picker.Model = pickerViewModel;
        picker.ShowSelectionIndicator = true;
        pickerViewModel.SelectedItemChanged += vm_SelectedItemChanged;
        var textView = new PaddedUITextField( new RectangleF( 10, 50 + i * 40, 300, 30 ) );
        Add( textView );
        textView.InputView = picker;
        _pickers.Add( picker );
        _textViews.Add( textView );
        currentSet.Bind( textView ).For( t => t.Text ).To( "SelectedColourCodeParts[" + i + "]" );
        currentSet.Bind( pickerViewModel ).For( p => p.ItemsSource ).To( "ColourPartLists[" + i + "]" );
        currentSet.Bind( pickerViewModel ).For( p => p.SelectedItem ).To( "SelectedColourCodeParts[" + i + "]" );
        currentSet.Bind( pickerViewModel ).For( p => p.SelectedChangedCommand ).To( vm => vm.ColourCodePartChangedCommand ).CommandParameter( j );
    }
    currentSet.Apply();
    UpdateLayout( View.Frame.Size );
}

private void ClearPickers()
{
    foreach ( var picker in _pickers )
    {
        var vm = picker.Model as MvxPickerViewModel;
        vm.SelectedItemChanged -= vm_SelectedItemChanged;
        picker.RemoveFromSuperview();
    }
    foreach ( var textView in _textViews )
    {
        textView.RemoveFromSuperview();
    }
    _pickers.Clear();
    _textViews.Clear();
}  

我现在拥有的 Android 版本仅有部分(而不是完全)的大纲,具体如下:

private void InputColourAtlasChangedMessageHandler( InputColourAtlasChangedMessage message )
        {
            ColourAtlas selected = message.SelectedColourAtlas;
            var layout = FindViewById<LinearLayout>( Resource.Id.spinnerList );
            ClearPickers();

            for ( int i = 0; i < message.ColourCodePartCount; i++ )
            {
                MvxSpinner spinner = new MvxSpinner( Context??, Attrs??);
                MvxAdapter adapter = new MvxAdapter( this );

                spinner.ItemSelected += spinner_ItemSelected;
                layout.AddView( spinner );
                _spinners.Add( spinner );
            }
        }

        void spinner_ItemSelected( object sender, AdapterView.ItemSelectedEventArgs e )
        {
            var changedIndex = _spinners.IndexOf( sender as MvxSpinner );
            ( DataContext as ColorMatchViewModel ).ColourCodePartChangedCommand.Execute( changedIndex );
        }

        private void ClearPickers()
        {
            var layout = FindViewById<LinearLayout>( Resource.Id.spinnerList );
            foreach ( var spinner in _spinners )
            {
                spinner.ItemSelected -= spinner_ItemSelected;
            }
            layout.RemoveAllViews();
            _spinners.Clear();
        }

1
https://github.com/MvvmCross/MvvmCross-Tutorials/blob/master/ApiExamples/ApiExamples.Touch/Views/FirstView.cs#L138 和 https://github.com/MvvmCross/MvvmCross-Tutorials/blob/master/ApiExamples/ApiExamples.Droid/Resources/Layout/Test_Spinner.axml#L11 - 都使用数据绑定而不是代码后台。 - Stuart
谢谢Stuart,这给了我数据绑定部分的解决方案,但是我现在仍然有一个问题,就是如何在代码中以编程方式创建MvxSpinner?应该传递什么给它的构造函数? - Martin Zikmund
1个回答

5

这里有一个在Activity.OnCreate中通过代码创建mvxspinner的例子:

_bindingContext = new MvxAndroidBindingContext(this, new LayoutInflaterProvider(LayoutInflater), _viewModel);
var view = (LinearLayout)_bindingContext.BindingInflate(Resource.Layout.Main, null);
SetContentView(view);
var spinner = new MvxSpinner(this, null, new MvxAdapter(this, _bindingContext));
view.AddView(spinner);

然后,如果你想要的话,你的LayoutInflaterProvider可能会像这样:

public class LayoutInflaterProvider
    : IMvxLayoutInflater
{
    public LayoutInflaterProvider(LayoutInflater layoutInflater)
    {
        LayoutInflater = layoutInflater;
    }

    public LayoutInflater LayoutInflater { get; private set; }
}

I was initially looking at this tutorial.


谢谢您的回复,我唯一需要的是 LayoutInflaterProvider 类型,如何访问它? - Martin Zikmund
抱歉,那实际上是它自己的自定义类。你可以在这里找到它:https://github.com/MvvmCross/MvvmCross-Tutorials/blob/386d6b7e672e3289f6227255180b15bbd89f1534/CrossLight/PluginUse/Mvvm/Framework/LayoutInflaterProvider.cs。我也会更新我的答案。 - PkL728

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接