views:

423

answers:

2

Hello

I am using a CollectionViewSource in a dialog view model that has various filtering requirements, which works fine. I also maintain the equivalent of the selected item in a property (SelectedProject), and I'm wondering if I could / should do away with it since the View will know the current item. My data binding looks like:

   <ListView  
          ItemsSource="{Binding Projects.View}" 
          IsSynchronizedWithCurrentItem="True"
          SelectedItem="{Binding SelectedProject, Mode=TwoWay}"
                      >

I use the setter for the SelectedProject to facilitate unit testing, and the CurrentItem doesn't appear to be settable as far as I can see. I also need to cast it to the right object when I want to use it. OTOH, if the SelectedProject is redundant then I'd show it the same respect as any other redundancy and delete it.

So, how do you typically deal with the current item when you're using a CollectionViewSource?

Cheers,
Berryl

+1  A: 

Hi,

You need to understand that the SelectedItem from the ListView is independent of the ItemsSource. Whether you use a CollectionViewSource or a List or an Array, the selected item will alway represent the item of that collection.

So to answer your question, as to why your SelectedProject is not setting, I suggest you check your setter functionality for errors. A good way to find out if the binding contains any errors is to check our Output for any binding error messages during debug.

NOTE: If your SelectedProject is the same type as the items in your Projects CollectionViewSource, then you needn't to cast it before usage (unless you have made SelectedProject of Object type then that also explains your setting problem).

EDIT: Sorry, short answer is no, it is not redundant. Having a variable bound to the current item is not redundant if you have testing in mind. A good example is when you want to test an old version of the SelectedItem with the new. Now if you only refer to the CollectionViewSource's SelectedItem, then it may be too late to compare, but with your own variable, you can test the logic before you set it again.

Tri Q
The SelectedProject works perfectly - the question was whether it's redundant to the ColloctionViewSource CurrentItem.
Berryl
+2  A: 

You could do away with the SelectedProject, but I would argue against it. If you have the property in your code, it is clear what you are doing. If you don't have it, you will need to do something like

CollectionViewSource.GetDefaultView(Projects.View).CurrentItem as Project

just to interact with the current project. I value clarity over "built-in". On top of that, CurrentItem is read-only, so if you ever want to select an item in the ViewModel, it wouldn't be possible.

Abe Heidebrecht
You can set the current item with various Move methods but I agree the readability is worth the arguable redundancy. Cheers
Berryl