将 ICommand 属性添加到列表中的每个项目:
public class ItemViewModel
{
public string MenuName { get; set; }
public string Icon { get; set; }
public Type PageType { get; set; }
public ICommand ItemTappedCommand { set; get; }
}
创建视图模型列表并设置命令以接收所需的参数作为参数;
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;
}
在 XAML 视图中,将所需的值作为命令参数传递;
<ListView ItemsSource="{Binding ItemsViewModel}" >
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding MenuName}"
Command="{Binding ItemTappedCommand}"
CommandParameter="{Binding PageType}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>