Emulating the IsSynchronizedWithCurrentItem Behavior in XamDataGrid

In WPF programming, you often set a list control’s IsSynchronizedWithCurrentItem property to true so that selecting an item in the list will cause the rest of the UI to treat that item as the “current” item to display.  In addition, by setting that property to true, if some other control (or line of code) decides to set the current item to a new value, the list control will automatically select that item.  This is based on the CurrentItem property of WPF’s built-in ICollectionView interface.  You can learn more about this feature of WPF in my MSDN article, ‘Customizing Data Display with Data Binding and WPF’.

XamDataGrid does not yet have a property similar to IsSynchronizedWithCurrentItem.  In this blog post, I provide a class that will emulate that functionality.  Once the control has native support for this functionality, my stopgap solution will be unnecessary.

I decided to expose this functionality as an attached behavior, so that it is easy to use it from XAML. The XAML below demonstrates how to use the feature:
NOTE: The XamDataGrid's DataContext *must* reference the data source,
otherwise the current item sync behavior will not work.  In this demo,
the DataContext is inherited from the Window, and the DataSource property
is bound directly to the DataContext.

When you run the demo app, you will see a XamDataGrid and a ListBox, both bound to the same data source.  In the screenshot below, I’ve select an item in one control and it is, due to the magic of ICollectionView, selected in the other control.  

In the next screenshot, you can see that I deleted the item with the name ‘David’ from one control, and it is removed from both (because they are both bound to the same data source).  Also, notice that both controls now have the item with the name ‘Paco’ selected.  All of this happens automatically, since both controls rely on WPF's built-in support for currency management.

I must point out some limitations.  It only works properly if the XamDataGrid is showing flat data.  If your data source is hierarchical, when you select a child record, the rest of the UI will not recognize the new current item, because it is not in the collection of items to which they are bound.  Also, ICollectionView does not support having multiple current items, which means you cannot have multiple selected records in the XamDataGrid that correspond to multiple selected items elsewhere in the UI.  That is a limitation imposed by WPF, not the grid control or my implementation.

Download the source code here.  The project compiles in Visual Studio 2008 using NetAdvantage for WPF v8.1.

Tags /