Reputation: 2195
I have a ListView, ItemsSource bound to the ViewModel, and the items are a custom class (containing the Name of the menu, the Icon, and a Type that is of a Page, which will be launched upon tapping the menu point).
I've discovered that it is possible to bind a Command to a TextCell, and I wish to do so. But as in my case, the list is not fixed, but generated, I am yet to find a solution.
ElementName in Binding does not work, nor does the xmlns:local definition.
Is there a way to use the Command binding, or should I just stick with the ListView.ItemTapped event?
Upvotes: 0
Views: 3644
Reputation: 1239
Add an ICommand property to each item in the list:
public class ItemViewModel
{
public string MenuName { get; set; }
public string Icon { get; set; }
public Type PageType { get; set; }
public ICommand ItemTappedCommand { set; get; }
}
Create the view model list and setup the command to receive desired argument as parameter;
public List<ItemViewModel> CreateItemsViewModel(List<Item> items)
{
var list = new List<ItemViewModel>();
foreach (var item in items)
list.Add(new ItemViewModel()
{
MenuName = item.MenuName,
Icon = item.Icon,
PageType = item.PageType,
ItemTappedCommand = new Command<Type>((type) =>
{
OpenPageOfType(type);
})
});
return list;
}
In a XAML view, pass required value as command parameter;
<ListView ItemsSource="{Binding ItemsViewModel}" >
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding MenuName}"
Command="{Binding ItemTappedCommand}"
CommandParameter="{Binding PageType}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Upvotes: 1