开发者

WPF DataGrid Binding and CheckBox

I have a fundamental question:

Let's say I have a List of elements of some class. And I also have a DataGrid that displays the properties of the items of this list. I want a user to select some items via the extra checkbox开发者_运维百科 column (datagridtemplatecolumn in fact). Then he presses the button and only selected items are processed by some function. How should I implement the logic of this checkbox?

  1. Should I add a boolean property to my class and bind it to the checkbox column? (I think, it's not good to add an extra property to my core class just for the sake of UI)

  2. Should I make some wrapper class that has a boolean property and bind DataGrid to the list of wrapper class? (Better complies to the OOP rules than the first variant)

  3. Make an unbound checkbox column. And then check the datagrid rows in the loop to gather selected items before processing. (This is what I wanted to do, but unbound checkbox column behaves really strange : when I toggle one checkbox, a couple of others are toggled as well. And I also didn't find a way to look through all the Rows of the DataGrid).

  4. Your variant...

And I want to do that stuff according to OOP rules. This is the main requirement. That's why I cannot accept the first variant, unless you say me that it's OK and commonly used.


I vote for #2; it gels with the MVVM pattern which I think is the only way to do straight-forward development in WPF. In this way you would make a view-model class that wraps your domain object to handle the communication between checking boxes and changing properties, etc., all the while firing PropertyChanged events and keeping your UI up-to-date.


guys I just try this solution and work great, maybe is not the best but it work.

bool? valor = false;
                foreach (var d in DetalleFactura.Items)
                {
                    DataGridRow row = (DataGridRow)DetalleFactura.ItemContainerGenerator.ContainerFromItem(d);
                    if (DetalleFactura.Columns[0].GetCellContent(row) is CheckBox)
                    {
                        valor = ((CheckBox)DetalleFactura.Columns[0].GetCellContent(row)).IsChecked;

                    }

                }


We had struggled with the same dilemma and ultimately ended up with option #1 of adding a boolean property to the class of IsSelected Why? When it really came down to it:

  • it was the easiest
  • could be re-purposed for any type of binding
  • and finally... because Josh Smith uses IsSelected*

Sure, this may violate some golden MVVM rule, but sometimes, rules are meant to be broken.


*I can't recall the exact example Josh provided, but you can see his usage in one of his blog posts: The Initially Selected Item when Binding to a Grouped ICollectionView

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜