Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding SelectedItem vs SelectedIndex - When should I choose one over the other?

Tags:

c#

mvvm

wpf

xaml

Let's say that you have an observable collection of object type Foo, and you have a custom ListView that the user will select from.

Your bound data object:

// property with getter / setter / INotifyPropertyChanged
ObservableCollection<Foo> MyCollection; 

In XAML:

<ListView ItemsSource={Binding MyCollection} />

Is it more appropriate to bind to the SelectedIndex in XAML and create the following in your data object:

int SelectedIndex { get; set; } // also raising property changed notifications
Foo SelectedObject
{
   get { return MyCollection[SelectedIndex]; }
}

Or to create this and bind to the SelectedItem in XAML:

Foo SelectedObject { get; set; } // also raising property changed notifications

And why?

like image 418
Clark Avatar asked Sep 24 '14 14:09

Clark


1 Answers

Both cases are acceptable, however which you choose usually depends on the design of your data models, and which method would require the least amount of code to get working.

A few rules I use to determine which one to select

  1. If SelectedObject cannot be null (such as an enum), and you need to default to be no item selected, then use SelectedIndex.

  2. If SelectedObject may not be considered .Equals() to any item in your Items list, use SelectedIndex. This is because SelectedItem compares objects with the Items collection using .Equals(), so a reference comparism will return false which will result in your object not becomming selected.

    This usually happens when your selected item comes from a different location than where your list of items is. For example, one database calls to load the Items for the list, and a separate database call obtaining an object that includes a SelectedObject property.

  3. If you need to reference only one of SelectedObject or SelectedIndex in other parts of your code, use that one.

  4. If your data models already have a SelectedIndex or SelectedObject property, then use that.

  5. If all other things are equal, I use a SelectedObject property to bind the SelectedItem property.

    This is because to me it makes more sense to refer to something like SelectedUser instead of SelectedUserIndex in the code behind, and I prefer to avoid looking up the item in the collection anytime I want to do something with the selected item.

like image 144
Rachel Avatar answered Sep 29 '22 16:09

Rachel