Wednesday, March 24, 2010

Attached Behaviors

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.

namespace MyProject.AttachedBehaviors
{
public class DataGridBehavior
{
#region AutoScrollIntoView

public static bool GetAutoScrollIntoView(DataGrid dataGrid)
{
return (bool)dataGrid.GetValue(AutoScrollIntoViewProperty);
}

public static void SetAutoScrollIntoView(
DataGrid dataGrid, bool value)
{
dataGrid.SetValue(AutoScrollIntoViewProperty, value);
}

public static readonly DependencyProperty AutoScrollIntoViewProperty =
DependencyProperty.RegisterAttached(
"AutoScrollIntoView",
typeof(bool),
typeof(DataGridBehavior),
new UIPropertyMetadata(false, OnAutoScrollIntoViewWhenSelectionChanged));

static void OnAutoScrollIntoViewWhenSelectionChanged(
DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
DataGrid dataGrid = depObj as DataGrid;
if (dataGrid == null)
return;

if (!(e.NewValue is bool))
return;

if ((bool)e.NewValue)
dataGrid.SelectionChanged += OnDataGridSelectionChanged;
else
dataGrid.SelectionChanged -= OnDataGridSelectionChanged;
}

static void OnDataGridSelectionChanged(object sender, RoutedEventArgs e)
{
// Only react to the SelectionChanged event raised by the DataGrid
// Ignore all ancestors.
if (!Object.ReferenceEquals(sender, e.OriginalSource))
return;

DataGrid dataGrid = e.OriginalSource as DataGrid;
if (dataGrid != null && dataGrid.SelectedItem != null)
dataGrid.ScrollIntoView(dataGrid.SelectedItem);
}

#endregion // AutoScrollIntoView

}
}

Now is XAML you will need to reference the above namespace:

xmlns:localBehaviors="clr-namespace:MyProject.AttachedBehaviors"

And use it in your DataGrid in the following manner whenever you like to see such behavior.

<wpfToolkit:DataGrid 
EnableColumnVirtualization="True"
VirtualizingStackPanel.VirtualizationMode="Recycling"
Grid.Row="0"
DataContext="{Binding}"
ItemsSource="{Binding Path=Entities}"
SelectedItem="{Binding
Path=EntityNavigation.CurrentEntity,
UpdateSourceTrigger=PropertyChanged,
Mode=TwoWay,
Converter={StaticResource ChildToParentEntityViewModelConverter}}"

localBehaviors:DataGridBehavior.AutoScrollIntoView="True"

...
/>

This (localBehaviors:DataGridBehavior.AutoScrollIntoView="True") last line in the XAML markup above will do it.

This was another ISolvable<TProblem>.

Happy Coding!

3 comments:

  1. The above attached behavior may crash when IsVirtualizing is set to true. To avoid that please see my new post with a work around.
    http://isolvable.blogspot.com/2010/03/wpf-datagrid-scrollintoview.html

    ReplyDelete
  2. Thanks! Good job!

    ReplyDelete
  3. Thanks! I was on the right track, but couldn't quite get it. Great post.

    ReplyDelete