How can I add a "select" column to a Silverlight DataGrid w/MVVM
I need to have a column with checkboxes in my DataGrid for the user to select various rows (that an operation would be performed on later). The grids ItemsSource is bound t开发者_如何学Goo an ObservableCollection. My quickest solution (not the best, but just to get it working) I thought would be to inherit from the class in the collection, adding in an IsSelected property I could bind to and just work from there. However, the collection I'm starting with is already instantiated, and downcasting/contravariance isn't working for me. And, it wouldn't be feasible to recreate a collection of the derived class.
So, I'm looking now for a simple solution with maybe an attached behavior on a checkbox column. I'm trying not to spend too much time on this, so I need some ideas.
I think what you're doing is a good way to do it. The subclass you're using is kind of a "ViewModel" for the original class.
However, there is another way that I found in this post by Laurent Bugnion that uses the SelectedItems
collection of the DataGrid
control, which you can't bind to directly, unfortunately, because it's not a DependencyProperty
, but he uses the EventToCommand
behavior from his MVVMLight Toolkit and passes the SelectedItems
collection as a CommandParameter
.
I hope this helps ;)
I eventually had to do it this way:
1) Use a CheckBox inside a TemplateColumn instead of the DataGridCheckBoxColumn because the DataGridCheckBoxColumn doesn't have Checked & Unchechecked events to hook into.
2) Create a behavior class for the Checked and Unchecked events on the checkbox, with seperate commands for each; I had to create a behavior class because while the CheckBox has a Command property already, there didn't seem to be any way of determing the checked/unchecked status of the control, unless used as a CommandParameter, which I needed to pass information for the DataGrid bound item in.
3) Pass in a reference to the VM from the View, and declare the VM as a static resource in code behind; I had to do it this way in order to bind to the commands in my VM with the checkbox, while having access to the same Observab
精彩评论