I am writing an application that uses two grid controls. If the user selects a row in the left grid control, the corresponding row in the right grid control must be selected from code. For both grids I am using a grid control derived class that allows the user to select multiple rows at the same time.The code to select a row from code works, the problem I am facing is that (apparently) other rows are not properly unselected. When selecting multiple rows afterwards in the right grid control (by clicking a row and then another one using shift+click) a lot more rows are selected than expected.
public class CustomDataGrid : DataGrid
{
public CustomDataGrid()
{
SelectionChanged += CustomDataGrid_SelectionChanged;
}
void CustomDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedItemsList = SelectedItems;
}
#region SelectedItemsList
public IList SelectedItemsList
{
get { return (IList)GetValue(SelectedItemsListProperty); }
set { SetValue(SelectedItemsListProperty, value); }
}
public static readonly DependencyProperty SelectedItemsListProperty =
DependencyProperty.Register("SelectedItemsList", typeof(IList), typeof(CustomDataGrid), new PropertyMetadata(null));
#endregion
}
In the xaml file it is used like this:
<vm:CustomDataGrid ItemsSource="{Binding LeftGridItems}" SelectedItemsList="
{Binding SelectedLeftGridItems, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
AutoGenerateColumns="False" SelectionMode="Extended" IsReadOnly="True"
CanUserAddRows="False" Margin="7,0,7,7" Grid.Row="3" Grid.Column="0">
<DataGrid.Columns>
...
The code for the selection in the left grid:
public IList SelectedLeftGridItems
{
get { return _selectedLeftGridItems; }
set
{
_selectedLeftGridItems = value;
// Select the copy on the right side, if available
if (_selectedLeftGridItems != null && _selectedLeftGridItems.Count > 0)
{
Element selected = ((Element)SelectedLeftGridItems[0]);
if (!string.IsNullOrEmpty(selected.CopyOf))
{
SelectedRightGridItems.Clear();
SelectedRightGridItems.Add(RightGridItems.FirstOrDefault(e => Path.GetFileName(e.Path) == Path.GetFileName(selected.CopyOf)));
OnPropertyChanged("SelectedRightGridItems");
}
}
OnPropertyChanged("SelectedLeftGridItems");
}
}
How can I ensure that the selected items in the right grid are properly administered?