Johan Karlsson: Navigation from a ListView

The problem to be solved

One drawback with the vanilla ListView that comes with Xamarin.Forms is that once an item is selected it can’t be selected again until you select something else and reselect it. Usually this is fine, unless you use the ListView to navigate away to a new page. When you return you cannot re-navigate to the same page again.

The solution

The solution to this is simple, just hook up to the ItemSelected event for the ListView and set the SelectedItem property to null.

So the short version of you quick-googlers would be the following line of code. (in the View)

  // Reset the selected item to make it selectable again
  duckListView.ItemSelected += (s, e) => {
    duckListView.SelectedItem = null; 

And the navigation should be done in the ViewModel

        public Duck SelectedDuck
        {
            set 
            {
                if (value != null)
                {
                    // IoC omitted, we should really get someone else to 
                    // create these objects for us.
                    var viewModel = new DuckViewModel() { Duck = value };
                    var page = new DuckView(viewModel);
                    _navigation.PushAsync(page);
                }
            }
        }

The more verbose version

You could also navigate directly from this event handler, but you should feel it deep in your heart that that is just wrong. Instead we handle navigation in the ViewModel. I’ve created a sample project to do this. Also, I’m doing this without any additional framework that would handle navigation for you so that’s why I need to provide my ViewModel with a navigation interface.

I’ll present each file to you below or just download the sample solution from here.

The Model

Our model is simple. It’s just a duck with a name… As you might recall, a model could be anything really. In this case it’s a simple class.
    
    public class Duck
    {
        public string Name
        {
            get;
            set;
        }
    }

The ViewModel (s)

We’ve got two ViewModels, but it’s really only the MainViewModel that’s interesting. It initializes it’s own data, which usually should be done async from another source. It doesn’t implement INotifyPropertyChanged either, as is should but for this sample it’s good enough.

What to focus on is the SelectedDuck property that handles the navigation. We only implement a setter for this since we reset the selected item anyhow in the view itself and on top of that navigate away from the page.


    /// <summary>
    /// The sample ViewModel. Should implement INotifyPropertyChanged
    /// </summary>
    public class MainViewModel
    {
        private INavigation _navigation;

        public MainViewModel(INavigation navigation)
        {
            _navigation = navigation;

            Ducks = new List<Duck>()
            {
                new Duck() { Name = George },
                new Duck() { Name = Bob },
                new Duck() { Name = Sarah },
                new Duck() { Name = Clint },
            };
        }

        /// <summary>
        /// A list of ducks
        /// </summary>
        /// <value>The ducks.</value>
        public List<Duck> Ducks
        {
            get;
            set;
        }

        public Duck SelectedDuck
        {
            set 
            {
                if (value != null)
                {
                    // IoC omitted, we should really get someone else to 
                    // create these objects for us.
                    var viewModel = new DuckViewModel() { Duck = value };
                    var page = new DuckView(viewModel);
                    _navigation.PushAsync(page);
                }
            }
        }
    }

The other ViewModel (DuckViewModel) simply references the selected duck on the page we navigate to.

   public class DuckViewModel
    {
        public DuckViewModel()
        {
        }

        public Duck Duck
        {
            get;
            set;
        }
    }

The View

That leaves us with the view that consists of two parts; XAML and the code behind. Usually you don’t want any code expect the ViewModel-binding in the code-behind since it’s very platform coupled, but in this case we need to do an exception. We need to reset the SelectedItem property of the ListView.
    public partial class MainView : ContentPage
    {
        public MainView()
        {
            InitializeComponent();
            BindingContext = new MainViewModel(this.Navigation); // Should be injected

            // Reset the selected item to make it selectable again
            duckListView.ItemSelected += (s, e) => {
                duckListView.SelectedItem = null; 
            };
        }
    }


The XAML parts look like this.
xml version=1.0 encoding=UTF8?>
<ContentPage xmlns=http://xamarin.com/schemas/2014/forms xmlns:x=http://schemas.microsoft.com/winfx/2009/xaml x:Class=ListViewNavigation.MainView>
    <ContentPage.Content>

      <ListView x:Name=duckListView
             IsGroupingEnabled=false
             ItemsSource={Binding Ducks}
             HasUnevenRows=true
             SelectedItem={Binding SelectedDuck}>
    <ListView.ItemTemplate>
      <DataTemplate>
        <ViewCell>
            <Label Font=Large Text={Binding Name} />
        </ViewCell>
      </DataTemplate>
     </ListView.ItemTemplate>
    </ListView>

    </ContentPage.Content>
</ContentPage>

Summary

There is a lot missing in forms of Ioc and base frameworks for MVVM (like MvvmLight och MvvmCross). Is there an alternative for the extreme mvvm-purists? Yes, you could hook up a GestureRecognizer on each item in the ListView but some platform specific animations will be lost if you do so.

Please give feedback what ever you feel like! And if there’s a better way, I would love for you to enlighten me! 😀