Fix DataGrid row anchor not being set when programmatically updating selection #378
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
When a change to the selection of WPF's
DataGrid
is made programmatically it does not update the selection anchor, which is used for SHIFT selection. As a result, attempting SHIFT selection following a programmatic adjustment to the selection of aDataGrid
can result in unexpected selection behaviour for the end user.You can test this behaviour in the Showcase application by:
Without the fix in this pull request, the selection will select all the rows from row 3 to row 12, instead of row 5 to row 12.
What changed?
This change uses reflection to reference a private field in the
DataGrid
called_selectionAnchor
. In looking over the source code for WPF, I cannot see an alternative way of doing this using a public (or even protected) API, although it's possible there is a way. Although this field is private (and therefore could theoretically change at any time), this WPF code has been in place for many years and so appears stable as far as future changes go.In my own testing, this results in the selection anchor being set as expected and it all seems to behave fine, however I welcome input on this approach.