我一直在寻找我的问题的解决方案并尝试过多种方法,但我的命令从未成功绑定。您可以在我尝试过的代码中看到一些解决方案,但它们不起作用。我有一个click事件可以工作,但我真的需要在应用程序的ViewModel端使用该命令,否则我将不得不重复代码。我还尝试将MvxRecyclerView
与local:MvxBind="ItemClick NavigateMenuCommand"
绑定,但这也不起作用。
这是我试图绑定的命令:
public ICommand NavigateMenuCommand {
get { return new MvxCommand(() => NavigateMenu()); }
}
public void NavigateMenu()
{
// Just a placeholder to see if the command is working
Debug.WriteLine("Hello World");
}
这是我的主要活动:
protected override void OnViewModelSet()
{
SetContentView(Resource.Layout.Home);
/* This didn't work
var set = this.CreateBindingSet<HomeView, HomeViewModel>();
set.Bind(FindViewById<MvxRecyclerView>(Resource.Id.menuGrid)).For("ItemClick").To(vm => vm.NavigateMenuCommand);
set.Apply(); */
}
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
adapter = new Adapters.MenuItemRecylcerAdapter(this, Rpm.Data.Shared.User.AppList.ToArray());
adapter.ItemClick += OnItemClick;
view = FindViewById<MvxRecyclerView>(Resource.Id.menuGrid);
view.SetAdapter(adapter);
layoutManager = new GridLayoutManager(this, 3);
view.SetLayoutManager(layoutManager);
view.NestedScrollingEnabled = false;
}
这是我的ViewHolder:
public class MenuItemAdapterViewHolder : MvxRecyclerView.ViewHolder
{
public TextView description { get; set; }
public TextView icon { get; set; }
public MenuItemAdapterViewHolder(View itemView, Action<int> listener) : base(itemView)
{
description = itemView.FindViewById<TextView>(Resource.Id.itemDescription);
icon = itemView.FindViewById<TextView>(Resource.Id.itemIcon);
itemView.Click += (sender, e) => listener(base.Position);
}
}
这是我的适配器:
class MenuItemRecylcerAdapter : MvxRecyclerView.Adapter
{
Activity _context;
public Rpm.Models.Bases.Menu[] _menuItems;
public EventHandler<int> ItemClick;
public MenuItemRecylcerAdapter(Activity context, Rpm.Models.Bases.Menu[] menuItems)
{
_context = context;
_menuItems = menuItems;
}
public override int ItemCount => _menuItems.Count();
public override void OnBindViewHolder(MvxRecyclerView.ViewHolder viewHolder, int position)
{
var item = _menuItems[position];
var holder = viewHolder as MenuItemAdapterViewHolder;
holder.description.Text = item.Description;
holder.icon.SetTypeface(Typeface.CreateFromAsset(Application.Context.Assets, "Fonts/fontawesome-webfont.ttf"), TypefaceStyle.Normal);
holder.icon.Text = item.IconFont;
}
public override MvxRecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
var id = Resource.Layout.MenuItem;
var itemView = LayoutInflater.From(parent.Context).Inflate(id, parent, false);
return new MenuItemAdapterViewHolder(itemView, OnClick);
}
private void OnClick(int position)
{
ItemClick?.Invoke(this, position);
}
}