Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a parameter with MvvmCross MvxBind, on ItemClick, using an MvxGridView

I have a ViewModel that includes an ObservableCollection of LocationViewModel. These are displayed as tiles in a grid. Each LocationViewModel stores a LocationId that is passed as a parameter when a tile in the grid is clicked. The MvxCommand that gets called when an item is clicked looks something like this:

// Constructor
public MainViewModel()
{
    LocationSelectedCommand = new MvxCommand<string>(OnLocationSelected);
}

// MvxCommand calls this
private void OnLocationSelected(string locationId)
{
    // Open a new window using 'locationId' parameter
}

All of this works correctly with WPF. I can bind the LocationId as a CommandParameter.

<view:LocationTileView 
    Content="{Binding }" 
    Command="{Binding ElementName=groupView, Path=DataContext.LocationSelectedCommand}" 
    CommandParameter="{Binding LocationId}" 
/>

Is there an equivalent syntax in Android for passing a parameter? This doesn't work, but I'm looking for something like what is in the MvxBind line:

<Mvx.MvxGridView
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:numColumns="5"
    android:stretchMode="columnWidth"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    local:MvxBind="ItemClick LocationSelectedCommand=LocationId; ItemsSource LocationViewModels"
    local:MvxItemTemplate="@layout/locationtileview" />
like image 979
Josh Avatar asked Dec 26 '22 21:12

Josh


1 Answers

You can use MvxCommand<T> with an ItemClick

This will pass you the item back:

private Cirrious.MvvmCross.ViewModels.MvxCommand<StacksTableItem> _itemSelectedCommand;
public System.Windows.Input.ICommand ItemSelectedCommand
{
    get
    {
        _itemSelectedCommand = _itemSelectedCommand ?? new Cirrious.MvvmCross.ViewModels.MvxCommand<MyItem>(DoSelectItem);
        return _itemSelectedCommand;
    }
}

private void DoSelectItem(MyItem item)
{
    // do whatever you want with e.g. item.LocationId
}

If it helps, there are a few examples of this in https://github.com/slodge/MvvmCross-Tutorials/ - e.g. inside Daily Dilbert ListViewModel.cs

like image 152
Stuart Avatar answered Dec 28 '22 11:12

Stuart