tags:

views:

41

answers:

2

I want to bind a boolean field in my ViewModel to be set to true when a row in the datagrid is selected.

So I have this working with the Style trick. That is using in my theme:

Then in the XAML markup for the Datagrid: ItemContainerStyle = "{DynamicResource ItemSelection}"

But to me this seems very poor form. I'm not expecting property binding to be taking place in my styles area. Is there a better way to do this? As in isn't there some way to directly bind to the IsSelected value of the row?

A: 

Well, I won't go as far as saying that this is "very poor form". I think it's okay.

For simplicity, consider a ListBox for instance. If you are adding items to it manually, you'll end up with something like this:

<ListBox>
  <ListBoxItem IsSelected="{Binding IsSelectedProperty}">Item1</ListBoxItem>
  <ListBoxItem IsSelected="{Binding IsSelectedProperty}">Item2</ListBoxItem>
  <ListBoxItem IsSelected="{Binding IsSelectedProperty}">Item3</ListBoxItem>
</ListBox>

This looks "ok" right? You're binding directly from the actual control (i.e. ListBoxItems) to a property in your ViewModel. This somewhat answers your question. This is another way of binding the IsSelected property. You'll have to manually add items to the control though. And I'm not sure though how you're going to do this in a DataGrid.

Now, if you're going to specify an ItemsSource for the ListBox (or a DataGrid for that matter), you are somewhat telling the ListBox to auto-generate the ListBoxItems for you. And since you want the "IsSelected" property of all the ListBoxItems to be bound to your ViewModel, it makes perfect sense to define it in a Style.

karmicpuppet
It just seems to spread my binding and event logic across multiple areas (since I'm using a theme in a external XAML I have to put the binding there). No other bindings for fields, commands, etc have to go over in my style. So it seems very much the exception that months from now I might be searching for instead of going to the obvious place.
Mark
A: 

I agree the technique is messy. I've written a MultiSelectCollectionView class that might help - you can find it here: http://grokys.blogspot.com/2010/07/mvvm-and-multiple-selection-part-iii.html

You might also want to read the previous posts in the series to understand the problems with the Style/IsSelected technique.

Groky