Introduction

If you have multiple items controls like ListBoxes, which all share the same data source, this is the simplest method of synchronising the controls, so that they all show the same item selected. This is as demonstration to a WPF forum poster who was asking how it was done.

 

 

Building the Sample

Just download, unzip, open and run!

 

Description

In this sample, there are two listboxes.

Both share the same data source, but through their own ListCollectionViews, which are created in code.

 

C#
Edit|Remove
    ICollectionView collegeView = new ListCollectionView(playerDatabase); 
    collegeView.GroupDescriptions.Add(new PropertyGroupDescription("CollegeName")); 
    collegeView.SortDescriptions.Add(new SortDescription("CollegeName", ListSortDirection.Ascending)); 
    collegeView.SortDescriptions.Add(new SortDescription("FirstName", ListSortDirection.Ascending)); 
    lstCollege.ItemsSource = collegeView; 
 
    ICollectionView positionView = new ListCollectionView(playerDatabase); 
    positionView.GroupDescriptions.Add(new PropertyGroupDescription("PositionCode"new NFLPositionGrouper())); 
    positionView.SortDescriptions.Add(new SortDescription("PositionName", ListSortDirection.Ascending)); 
    positionView.SortDescriptions.Add(new SortDescription("FirstName", ListSortDirection.Ascending)); 
    lstPosition.ItemsSource = positionView;
 
To tie the two together, we bind both controls' SelectedItem property to a public property behind. in this case I have simply dumped it in the code-behind, and set the window's DataContext to itself.
C#
Edit|Remove
    Player _SelectedPlayer; 
    public Player SelectedPlayer 
    { 
        get 
        { 
            return _SelectedPlayer; 
        } 
        set 
        { 
            if (_SelectedPlayer != value) 
            { 
                _SelectedPlayer = value; 
                RaisePropertyChanged("SelectedPlayer"); 
            } 
        } 
    }
The SeletedItem bindings are two-way, so changes made in one control will bounce back to the other control. That is because we implemented INotifyPropertyChanged on the SelectedItem property.

 

There is only one problem with the selected state of controls. When they are unfocussed, they are greyed out. This is done by the triggers in the Listbox ControlTemplates.

To rectify this, we can tweak with the triggers of the control, or simply override the system brushes that are used by the triggers. This second method is what is shown below:

XAML
Edit|Remove
<Grid.Resources        <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}"  
        Color="{x:Static SystemColors.HighlightColor}"/> 
</Grid.Resources>

Source Code Files