We want to be able to see the details for a selected to-do list item. When we tap a row, we should navigate to the item in that row.
To do this, we need to add the following code:
- Open ViewModels/MainViewModel.cs.
- Add the SelectedItem property and the NavigateToItem method to the class:
public TodoItemViewModel SelectedItem
{
get { return null; }
set
{
Device.BeginInvokeOnMainThread(async () => await
NavigateToItem(value));
RaisePropertyChanged(nameof(SelectedItem));
}
}
private async Task NavigateToItem(TodoItemViewModel item)
{
if (item == null)
{
return;
}
var itemView = Resolver.Resolve<ItemView>();
var vm = itemView.BindingContext as ItemViewModel;
vm.Item = item.Item;
await Navigation.PushAsync(itemView);
}
The SelectedItem property is a property that we will data-bind to ListView. When we select a row in ListView, this property is set to the TodoItemViewModel object that represents that row. Since we can't really use Fody here to carry out its PropertyChanged magic (because of the need for a method call in the setter), we need to go old school and manually add a getter and a setter.
The setter then calls NavigateToItem, which creates a new ItemView view using Resolver. We extract ViewModel from the newly created ItemView view and assign the current TodoItem object that TodoItemViewModel contains. Confused? Remember that TodoItemViewModel actually wraps a TodoItem object and it is that item that we want to pass to ItemView.
We are not done yet. We now need to data-bind the new SelectedItem property to the right place in the view:
- Open Views/MainView.xaml.
- Locate ListView and add the attributes in bold:
<ListView x:Name="ItemsListView"
Grid.Row="1"
RowHeight="70"
ItemsSource="{Binding Items}"
SelectedItem="{Binding SelectedItem}">
The SelectedItem attribute binds the SelectedItem property's ListView view to the ViewModel property. When the selection of an item in ListView changes, the ViewModel property's SelectedItem property is called and we navigate to the new and exciting views.
The x:Name attribute is for naming ListView because we do need to make a small and ugly hack to make this work. ListView actually stays selected after the navigation is done. When we navigate back, it cannot be selected again until we select another row. To mitigate this, we need to hook up to the ItemSelected event of ListView and reset the selected item directly on ListView. This is not recommended because we shouldn't really have any logic in our views, but sometimes we have no other choice:
- Open Views/MainView.xaml.cs.
- Add the following code in bold:
public MainView(MainViewModel viewmodel)
{
InitializeComponent();
viewmodel.Navigation = Navigation;
BindingContext = viewmodel;
ItemsListView.ItemSelected += (s, e) =>
ItemsListView.SelectedItem = null;
}
We should now be able to navigate to an item in the list.