我一直在与mvvmcross合作两天,并且从未使用iOS之前我认为只是我不理解的东西。
我使用两列3行网格中的UICollectionView创建了我的主菜单,每个项目代表用户可以点击的不同位置。我可以从UICollectionViewSource覆盖“ItemSelected”,但是我无法访问实际的ViewModel而没有将它的引用传递给创建源....这对我来说不是正确的方法。
[MvxRootPresentation(WrapInNavigationController = true)]
public partial class MainPageView : MvxViewController
{
private MenuCollectionSource _menuCollectionSource;
List<MainMenuItem> menuItems;
public MainPageViewModel VM
{
get { return DataContext as MainPageViewModel; }
}
private void SetupMenuCollectionView()
{
......
collectionView.RegisterNibForCell(MainMenuCollectionViewCell.Nib, MainMenuCollectionViewCell.Key);
MainMenuItem.Init(menuItems);
_menuCollectionSource = new MenuCollectionSource(collectionView, MainMenuCollectionViewCell.Key, menuItems);
_menuCollectionSource.VM = VM; <----doesnt seem right.
collectionView.Source = _menuCollectionSource;
public class MenuCollectionSource : MvxCollectionViewSource
{
private UICollectionView _collectionView;
public List<MainMenuItem> Items { get; set; }
private MainPageViewModel _vm;
public MainPageViewModel VM
{
get { return _vm; }
set { _vm = value; }
}
}
使用此方法,我可以覆盖ViewSource中的ItemSelected,并执行类似
的操作( Cell is touched ->
Depending on cell enum/cell# - >
vm.NavigateToCorrectPage())
虽然这种方法有效,但我不认为它是处理这种情况的正确方法。 那么我接下来的想法是将源代码绑定为......(可能不是100%,试图记住我的脑袋)
set.CreateBinding(_menuCollectionSource) .For(s => s.SelectedCommand) .To(vm => vm.NavigateTo) .CommandParameter(_menuCollectionSource.SelectedItem)
但无论我尝试了什么,传递的param总是为null,好像所选的项目从未设置过,或者在设置之前调用了命令。
我的CollectionViewCell类非常基本
public enum NavigationLocation
{
Search Database,
Lists,
etc....
}
public partial class MainMenuCollectionViewCell : MvxCollectionViewCell
{
public static readonly NSString Key = new NSString("MainMenuCollectionViewCell");
public static readonly UINib Nib;
public string MainMenuLabel
{ get { return mainMenuLabel.Text; } }
public int MainMenuIndexNumber
{ get; set; }
protected MainMenuCollectionViewCell(IntPtr handle) : base(handle)
{
}
static MainMenuCollectionViewCell()
{
Nib = UINib.FromName("MainMenuCollectionViewCell", NSBundle.MainBundle);
}
public static MainMenuCollectionViewCell Create()
{
NSArray topLevelObjects = NSBundle.MainBundle.LoadNib("MainMenuCollectionViewCell", null, null);
MainMenuCollectionViewCell cell = Runtime.GetNSObject(topLevelObjects.ValueAt(0)) as MainMenuCollectionViewCell;
return cell;
}
internal void BindData(string label, string iconBundleName)
{
mainMenuLabel.Text = label;
mainMenuImage.Image = UIImage.FromBundle(iconBundleName);
}
}
没有绑定我在单元类中尝试过实际工作,甚至在创建时添加UITapGestureRecognizer导致实际点击崩溃。我已经没有想法,有没有人知道我不理解或缺少实际实现
( Cell is touched ->
GetCellMenuType - >
CallCorrectCommandFromViewModel)
谢谢
答案 0 :(得分:0)
使用来自 MvxBaseCollectionViewSource的EventHandler SelectedItemChanged
查看强>
set.Bind(yourCollectionViewSource).For(s => s.SelectionChangedCommand).To(vm => vm.CollectionItemSelected);
<强>视图模型强>
public ICommand CollectionItemSelected => new MvxCommand<ItemViewModel>((selectedItem) => { });