I have a simple Xamarin.Forms.ContentPage that displays menu items in a ListView
:
<ContentPage x:Class="Mob.Views.Public.MenuPage" ... >
<ScrollView>
<ListView ItemsSource="{Binding MenuItems}" ItemTapped="{Binding OnMenuItemTapped}">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Key}" />
<!-- How to pass the "{Binding Value}" to OnMenuItemTapped? -->
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ScrollView>
</ContentPage>
Code behind:
public class MenuPage : ContentPage
{
public MenuPage()
{
InitializeComponent();
BindingContext = new MenuViewModel();
}
private async void OnMenuItemTapped(object sender, ItemTappedEventArgs e)
{
await (this.BindingContext as MenuViewModel).OnMenuItemTappedAsync(/* MUST PASS THE VALUE HERE*/);
}
}
As you can see, the ItemsSource
is bound to the MenuItems
property of my ViewModel. This property is of type Dictionnary<string, string>
. The Key
is used to display the text of the items while the Value
should be passed as a parameter to OnMenuItemTapped
event.
class MenuViewModel : ViewModelBase
{
...
public IDictionary<string, string> MenuItems { get { return _menuItems; } set { SetProperty(ref _menuItems, value); } }
// public ICommand OnMenuItemTappedCommand { get; set; }
public MenuViewModel()
{
MenuItems = new Dictionary<string, string>();
MenuItems.Add("XXX", "PageX");
MenuItems.Add("YYY", "PageY");
MenuItems.Add("ZZZ", "PageZ");
// ...
// I would've prefere to bind the item tap using a command but I can't figure out how to
// OnMenuItemTappedCommand = new Command<string>(OnMenuItemTappedAsync);
}
public async Task OnMenuItemTappedAsync(string targetPage)
{
// await Navigation.PushModalAsync(...);
// --> depending on the targetPage
}
}
My goal is to navigate to the right page depending on the value passed to OnMenuItemTappedAsync
.
Note, I am trying to do "pure" MVVM here. Meaning I know that I should not use events and leave the code behind almost empty. But I can't figure out how to use commands in this context.
Any idea/advice how to achieve this?