Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the initial selected item when binding to a ListView's SelectedItem property

I have a Xamarin.Forms xaml page in which I am using a ListView to allow the user to pick a single item out of a list. I have bound the ListView's SelectedItem property to a property on my ViewModel and this works fine. As soon as the user changes the selected item the property in my viewmodel updates as well.

However, even though I initially set the property in my ViewModel to one of the values from the list, when the page loads the ListView's SelectedItem property is null, which in turn sets the ViewModel property to null as well. What I need is the other direction, I want the ListView to initially select the item that i've set in the VM property.

I can hack together a solution by writing extra code in the code behind file to explicitly set the initial selected item, but this introduces additional properties and complexity and is quite ugly.

What is the correct way to set the initial selected item of a ListView who's selected item is bound to a viewmodel property?

-EDIT-

I was asked to provide the code that I'm using for my binding. It's very simple, standard:

<ListView x:Name="myList" ItemsSource="{Binding Documents}" SelectedItem="{Binding SelectedDocument}">

the view model that is set as the binding context for the listview is instantiated before the page is created and looks like this:

public class DocumentSelectViewModel : ViewModelBase
{
    private Document selectedDocument;

    public List<Document> Documents
    {
        get { return CachedData.DocumentList; }
    }

    public Document SelectedDocument
    {
        get { return selectedDocument; }
        set { SetProperty(ref selectedDocument, value); 
    }

    public DocumentSelectViewModel()
    {
        SelectedDocuement = CachedData.DocumentList.FirstOrDefault();
    }
}

SetProperty is a function which simply rasies the INotifyPropertyChanged event if the new value is different from the old one, classical binding code.

like image 319
irreal Avatar asked Sep 10 '15 07:09

irreal


1 Answers

I am a little rusty on XAML but don't you need to make the binding two-way?

E.G.

{ Binding SelectedDocument, Mode=TwoWay }

As long as the SelectedDocument property change raises the INotifyPropertyChanged event then you should get the desired effect.

like image 59
JordanMazurke Avatar answered Sep 22 '22 10:09

JordanMazurke