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

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?

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
If SelectedObject cannot be null (such as an enum), and you need to default to be no item selected, then use SelectedIndex.
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.
If you need to reference only one of SelectedObject or SelectedIndex in other parts of your code, use that one.
If your data models already have a SelectedIndex or SelectedObject property, then use that.
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.

Depends on your needs. If you need to set the selected item, you need the second version. If you need the selected item's index, you need the first version. If you need neither, it's up to your personal preference.

Both approaches are fine. Use the one you find easier to use. I don't find myself relying on indices often, but your cases may be different.
If you look at MVVM libraries, Caliburn.Micro, for example, expects you to use SelectedObject approach. It explicitly supports this convention.
And note on collection properties. In general, it's better idea to have read-only auto-properties and set them in constructor (property change notification won't be necessary). It is not advised to change instances of collections. While WPF supports it, it's much easier to subsribe to collection events in your own code if the instance doesn't change.

I personal think bind to the SelectedObject is much cleaner unless you need access to the SelectedIndex
The only time I use SelectedIndex is when I want to set a default value of 0 to select the first item.

Related

Using ViewModels in ObservableCollections in Prism

As far as I know, the default way to use a ObservableCollection that is bound to a listview is with model classes as elements (ObservableCollection<MyModel>). So when a listview element is selected, we use NavigateAsync and pass the model, which then can be used by the ViewModel to "fill itself".
The problem with this approach is, that it's not possible to use ViewModel properties for binding in the listview.
For example:
I have a View, ViewModel and Model "PickList", which contains a collection of "PickLine" objects - each having a View, ViewModel and Model themselves. The PickLine object contains a property "PickedQuantity" and a property "OpenQuantity". Now in my PickList view, I don't want to bind these two to separate items (e.g. two labels), but I want to have one label to display both I a format like for example "PickedQuantity / OpenQuantity". I know this example can be solved by using multi binding or something like this. But that's not the meaning of it all.
My PickLine ViewModel already has a property "QuantityString", that I want to bind to the label of a listview element via DataTemplate. But how can I do this. Is it even possible?
Make a property that combines the two other properties and bind to that. E.g.:
public string FullQuantity {get {return $"{PickedQuantity} / {OpenQuantity}";}}
Then in the setter for PickedQuantity and OpenQuantity, you will want to call whatever PropertyChanged method you have set up to notify the bindings of a property change and pass in the FullQuantity property name so elements that are bound to FullQuantity get updated when either PickedQuantity or OpenQuantity are changed.
This way, you are only binding one label's text to one property and that label would get updated when either of the two quantity properties are changed.
Note: I am unfamiliar with Prism, but this approach should work regardless of the Mvvm framework in use.
Your PickListViewModel should expose a collection property whose items are of type PickLineViewModel (not PickLine).
Whether you need an ObservableCollection<PickLineViewModel> depends on where changes can happen - in service / model that initially created the PickLines or in the GUI or both. In any way, you have to make sure the changes are propagated from one side (the collection of view models) to the other (the collection of models). Google wrapping observable collection as a starter (hint: avoid two-way sync if possible). These blog posts are old but still relevant and make a good reading. A trivial wrapping is described in this answer.

Binding a property in a object list which is in-turn a property of another list from View to ViewModel

I have a property (text box) which is a part of a list. And that list is a property in another list (class). Now when I write something in that text box , the ancestor one should get updated. I have tried RaisePropertyChanged() but its not working out. Can anyone provide me with right syntax??
When binding lists you should take a look at INotifyCollectionChanged. RaisePropertyChanged propagates that the list itself (not just one item in it) changed. If bound to a GUI the GUI will check for a change and sees the same old list in place, so it takes no further action.

Bind ObservableCollection as source for different CollectionViewSource

I have an ObservableCollection<MyClass> named myCollection that should be binded to two CollectionViewSources (AllItems and SelectedItems).
AllItems's source property is binded to the myCollection. SelectedItems's source property should be bind to myCollection items which IsSelected == true.
public class MyClass : INotifyPropertyChanged
{
//fields and interface implementations
public string Name {//proper code};
public bool? IsSelected {//proper code};
}
// some where else in the MainWindow
AllItems.Source = myCollection;
SelectedItems.Source = myCollection.Where(input=>input.IsSelected==true);
Problem: Every thing is OK when the Window is loaded. But when the IsSelected value for some items in the myCollection is changed obviously it has no effect on the SelectedItems. So to overcome this problem I update the source property of the SelectedItems every time an IsSelected property is changed.
Question: How can I do these kind of binding so that there is no need to manually update the source property of the SelectedItems?
Thnaks.
First of all, you should unconditionally remove your manual filtering setup and replace it with something more appropriate. The choice of what to replace with depends mainly on what .NET version you are targeting.
If targeting .NET 4.5 then a simple solution is and instead enable live filtering on the collection view.
For earlier versions of .NET you will have to do some manual work no matter what, but it is better to just call Refresh on the collection view that re-bind your control. To do this, you should defer the filtering to the collection view itself by setting the Filter event handler from XAML.
After the changes in MyClass you should raise PropertyChanged Event.
If you already do this than you should look at your SelectedItems.Source in Debug mode. Maybe its the correct value already there but its not shown to you.
I mean if SelectedItems.Source belongs to some visible Elements - GUI - you should refresh it on the screen. Cause the other way the value is there but will not be shown till your Element on the Screen is repainted.

Determining out the correct property return type for a data binding when using MVVM Light in a C#/WPF app?

I have a C# Windows Phone 7.1 project that uses the MVVM Light toolkit. On one application page in the app I have a Telerik data bound list box that is bound to a property in my view model. At first that property had a return type of:
List<string>
With that return type the property did not show up in the list of candidate elements in the Path list box, when I activated the Create Data Binding dialog box in order to assign the list box's ItemsSource property. However, when I changed that property's return type to:
ObservableCollection<string>
it showed up immediately. In the future, how can I determine the correct return type for a particular control's ItemsSource or other data bindable property?
Your question is little confusing. Both are completely okay and work well for different scenarios. You use list<string> when you don't plan to change collection, and ObservableCollection otherwise.
Now, you can use MSDN(see ItemsSource property to see what property needs to be what.
As you can see from documentation, ItemsSorce has to be IEnumerable, meaning all types that derive from it, can be used.
Now as for the real question, why didn't your property show up in the IDE, I can only guess that Microsoft wants you to use ObservableCollection always, but I don't agree with this. So that's why it's best to manually do the bindings to properties through Xaml.

WPF Databinding Magic

I have ObservableCollection<Foo> that is bound to an ItemsControl (basically displaying a list).
Foo mostly looks like this (there are other members but it doesn't implement any interfaces or events):
class Foo
{
public string Name { get; set; }
//...
}
When the user clicks on an item I open a dialog where the user can edit Foo's properties (bound to a small viewmodel with a Foo property for the selected item), the Xaml looks like this:
<TextBox Text="{Binding Foo.Name,Mode=TwoWay}"
Grid.Column="1" Grid.Row="0" Margin="2" />
The really strange thing is, when the user edits the name, the value in the list changes! (not while typing but after the focus leaves the field)
How does it do that? I haven't implemented the INotifyPropertyChanged interface on the Foo object!
So far I checked that it doesn't just refresh the whole list - only the selected item. But I don't know where I could set a breakpoint to check who's calling.
Update: thanks to casperOne for the link to the solution! I'll add a summary here in case it goes 404:
[..] actually you are encountering a another hidden aspect of WPF, that's it WPF's data binding engine will data bind to PropertyDescriptor instance which wraps the source property if the source object is a plain CLR object and doesn't implement INotifyPropertyChanged interface. And the data binding engine will try to subscribe to the property changed event through PropertyDescriptor.AddValueChanged() method. And when the target data bound element change the property values, data binding engine will call PropertyDescriptor.SetValue() method to transfer the changed value back to the source property, and it will simultaneously raise ValueChanged event to notify other subscribers (in this instance, the other subscribers will be the TextBlocks within the ListBox.
And if you are implementing INotifyPropertyChanged, you are fully responsible to implement the change notification in every setter of the properties which needs to be data bound to the UI. Otherwise, the change will be not synchronized as you'd expect.
This is a total guess, but I'm thinking that because you have two-way binding enabled, WPF is now aware of when it makes changes, and will update other items it knows is bound to the same instance.
So because you have changed the value of the Name property through the textbox, and WPF knows when you have changed that value, it does its best to update whatever else it knows is bound to it.
It uses reflection to set the value of that property. INotifyPropertyChanged is only needed if the TextBox needs to be informed of a change in the Name property of the Foo class.
Because they're databound to the same object. If you change the binding to
{Binding Foo.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}
then they'll be in synch when the user types in the textbox.

Categories