Hello,
Welcome to our Microsoft Q&A platform!
First of all, ItemTapped
is an event, it is not a command. If you want to achieve click command for Item in the Listview with MVVM.
You can use Command
from TextCell
like following code format. Use CommandParameter
to transfer current model data to the viewModel's Command.
I write three commands for TextCell click and two MenuItem
s.
<ListView x:Name="WorkoutsList"
ItemsSource="{Binding WorkoutsListSource}"
>
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding WorkoutName}"
Detail="{Binding Description}"
Command="{Binding Path=BindingContext.NaviCommand, Source={x:Reference Name=WorkoutsList}}"
CommandParameter="{Binding .}"
>
<TextCell.ContextActions>
<MenuItem x:Name="ChangeBtn"
Text="Ändra"
Command="{Binding Source={x:Reference Name=WorkoutsList}, Path=BindingContext.ChangeCommand}"
CommandParameter="{Binding .}">
</MenuItem>
<MenuItem x:Name="DeleteBtn"
Text="Ta bort"
IsDestructive="True"
Command="{Binding Source={x:Reference Name=WorkoutsList}, Path=BindingContext.DeleteCommand}"
CommandParameter="{Binding .}">
</MenuItem>
</TextCell.ContextActions>
</TextCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Here is layout background code.
public MainPage()
{
InitializeComponent();
this.BindingContext = new MyViewModel();
}
In the MyViewModel, I add three Command(called NaviCommand, ChangeCommand , DeleteCommand ), If click item. NaviCommand will execute, we can get the current item's data by key
property.
public class MyViewModel
{
public ICommand NaviCommand { protected set; get; }
public ICommand ChangeCommand { protected set; get; }
public ICommand DeleteCommand { protected set; get; }
public ObservableCollection<MyModel> WorkoutsListSource { get; set; }
public MyViewModel()
{
WorkoutsListSource = new ObservableCollection<MyModel>();
NaviCommand = new Command<MyModel>((key) =>
{
MyModel person = key as MyModel;
});
ChangeCommand = new Command<MyModel>((key) =>
{
MyModel person = key as MyModel;
});
DeleteCommand = new Command<MyModel>((key) =>
{
MyModel person = key as MyModel;
});
WorkoutsListSource.Add(new MyModel() { WorkoutName="test1", Description= "this is a Description1" });
WorkoutsListSource.Add(new MyModel() { WorkoutName = "test2", Description = "this is a Description2" });
WorkoutsListSource.Add(new MyModel() { WorkoutName = "test2", Description = "this is a Description3" });
WorkoutsListSource.Add(new MyModel() { WorkoutName = "test2", Description = "this is a Description4" });
}
}
public class MyModel
{
public string WorkoutName { get; set; }
public string Description { get; set; }
}
Best Regards,
Leon Lu
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.