在MvxDropDownItemTemplate中使用Button的MvxSpinner

时间:2013-08-18 02:56:58

标签: android mvvmcross

我希望MvxSpinner有一个下拉模板,里面有一个按钮。按钮单击会打开一个webbrowser,其中包含有关该项目的信息。按钮单击工作正常,但现在无法选择该项目。有办法解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

我想出了一种方法来完成这项工作。不确定这是否是最佳做法,但它对我有用。

我为Spinner创建了几个视图模型的ItemsSource。按钮单击的命令和事件处理项目中的任何其他触摸。我将MvxSpinner和MvxAdapter子类化。在子类适配器中,我将事件分配给处理程序,该处理程序以编程方式单击后退按钮以关闭下拉列表。我还将一个方法从适配器路由到微调器,以便设置所选项目。

public class ButtonSpinner : MvxSpinner
{
    public ButtonSpinner(Context context, IAttributeSet attrs) : base(context, attrs)
    {
        var adapter = new ButtonAdapter(context, routedItemClick);
        adapter.ItemTemplateId = Adapter.ItemTemplateId;
        adapter.DropDownItemTemplateId = Adapter.DropDownItemTemplateId;
        adapter.SimpleViewLayoutId = Adapter.SimpleViewLayoutId;
        this.Adapter = adapter;
    }

    private void routedItemClick(object sender, ItemClickEventArgs e)
    {
        this.SetSelection((int)sender);
    }
}

public class ButtonAdapter : MvxAdapter
{
    EventHandler<Android.Widget.AdapterView.ItemClickEventArgs> _routedItemClick;
    View _parent;

    public override IEnumerable ItemsSource {
        get {
            return base.ItemsSource;
        }
        set {
            base.ItemsSource = value;
            if (value != null)
            {
                foreach(var item in value)
                {
                    var dialectItem = item as DialectItemViewModel;
                    dialectItem.DialectSelected += (object obj, EventArgs args) => {
                        var dialectItems = ItemsSource as List<DialectItemViewModel>;
                        _routedItemClick(dialectItems.IndexOf(dialectItem), null);

                        _parent.RootView.DispatchKeyEvent(new KeyEvent(KeyEventActions.Down, Keycode.Back));
                        _parent.RootView.DispatchKeyEvent(new KeyEvent(KeyEventActions.Up, Keycode.Back));
                    };
                }
            }
        }
    }

    public ButtonAdapter(Context context, EventHandler<Android.Widget.AdapterView.ItemClickEventArgs> routedItemClick) : base(context)
    {
        _routedItemClick = routedItemClick;
    }

    protected override Android.Views.View GetView (int position, Android.Views.View convertView, Android.Views.ViewGroup parent, int templateId)
    {
        if (_parent == null)
            _parent = parent;

        return base.GetView (position, convertView, parent, templateId);
    }
}