It is kind of late in the game, but I thought I would cover how to bring WPF DataGrid selected item into view using Attached Behaviors. There is a nice article by Josh Smith which covers Attached Behaviors in more details. I will just cover a specific case with DataGrid.
When you are using MVVM sometimes there is a business need to change selected item from ViewModel and when it happens occasionally users will need to manually scroll to that item. This could be very confusing to the user. The desired behavior would be to scroll selected item into the view automatically.
There are multiple ways to solve this problem:
- Create an event handler for DataGrid.SelectionChanged event. If you however have multiple DataGrids in your project your code behind file will be polluted with these handlers. This is exactly the case why we are using MVVM to avoid code in code behind files and have a clear separation of concerns.
- Second approach will require extending DataGrid class and adding desired behavior. This is an overkill, since now everybody on the project will need to remember to use custom DataGrid. And if there are many of them it requires changes.
- Third approach using Attached Behaviors is very lightweight, “XAML friendly” and preserves MVVM separation of concerns. All you need is to create a separate class which can be used sparingly as developers see fit, it can sit in your project and be handy when need arises.
Below is an example of such class I used for DataGrid.
Now is XAML you will need to reference the above namespace:
And use it in your DataGrid in the following manner whenever you like to see such behavior.
This (localBehaviors:DataGridBehavior.AutoScrollIntoView="True") last line in the XAML markup above will do it.
This was another ISolvable<TProblem>.