开发者

Datagrid row IsSelected binding

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?


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.


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.


If you just want a boolean property in your viewmodel to be set to true when a row is selected in your grid, then you just have to bind a first property that represents your model in the dataSource to the grid property "SelectedItem".

After that your Boolean property only need to have a get that return a comparison to null of your first property.

ex:

private MyModel __selectedItem;
public MyModel SelectedItem
{
    get {   return _selectedItem; }
    set { 
            if (_selectedItem != value)
            {
                _selectedItem = value;
                RaisePropertyChange("SelectedItem");
            }
        }
 }

 public bool IsItemSelected => SelectedItem != null;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜