KrispyDonuts
KrispyDonuts

Reputation: 1262

Item is being selected in ListView on page load

I have a ListView in my xaml, and it's ItemsSource and SelectedItem property is binded to a ViewModel.

Xaml

<ListView ItemsSource="{Binding SitesCollection}" SelectedItem="{Binding SelectedSite, Mode=TwoWay}">
    <ListView.ItemTemplate>
        <DataTemplate>
              <TextBlock Text="{Binding url}"></TextBlock>
         </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

ViewModel

public ObservableCollection<AWRestrictedSite> _SitesCollection;
public ObservableCollection<AWRestrictedSite> SitesCollection
{
     get
     {
          //populate collection
          return _SitesCollection;
     }
}

public AWRestrictedSite _SelectedSite;
public AWRestrictedSite SelectedSite
{
      get
      {
          return _SelectedSite;
      }
      set
      {
          _SelectedSite = value;
          //do some stuff
      }
 }

For some reason when the page loads, it selects the first item in the ListView. Here is what happens when the page loads:

  1. Get inside SitesCollection is being called, (which populates the listview and returns the collection).
  2. Get inside SelectedSite is called, which returns null
  3. Set inside SelectedSite is called which sets the value to the first item

Does anyone know why this could be happening?

Upvotes: 2

Views: 581

Answers (2)

rohHit naik
rohHit naik

Reputation: 11

This usually happens when we set the SelectedItem of a ListView to ItemsSourceCollection.FirstOrDefault()

Upvotes: 0

roryok
roryok

Reputation: 9645

Its a two way bind, and when loaded, ListView (I think) selects the first item in its bound collection. Try adding a Loaded method to the ListView and setting the SelectedItem in there. This should happen after the first item is selected.

Upvotes: 0

Related Questions