ここに PreviewMouseDown メソッドの例がいくつかあります。
一般的な合意は、データグリッドの SelectionChanged ハンドラー内で DataGrid.SelectedItem を元の値に戻すことは期待どおりに機能しないということです。機能しているように見えるすべてのコード例は、ディスパッチャーに後でスケジュールするように依頼して、反転を延期します。
データグリッドに CellStyle がありますか? 私にとっては、以下が機能しました:
xaml:
<DataGrid.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="DarkSlateBlue"/>
<Setter Property="Foreground" Value="White"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
コードビハインド:
private void MyDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0)
{
object x = e.AddedItems[0];
if (x is MyObjectType && x != myViewModel.CurrentItem &&
myViewModel.ShouldNotDeselectCurrentItem())
{
// this will actually revert the SelectedItem correctly, but it won't highlight the correct (old) row.
this.MyDataGrid.SelectedItem = null;
this.MyDataGrid.SelectedItem = myViewModel.CurrentItem;
}
}
}
ポイントは、SelectedCellsChanged イベントが SelectionChanged イベントの後に発生したことです。特に、SelectedItem を設定しても、読み取り専用プロパティである SelectedCells が正しく更新されないため、分離コードがさらに必要です。
private void MyDataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
List<DataGridCellInfo> selectedCells = MyDataGrid.SelectedCells.ToList();
List<MyObjectType> wrongObjects = selectedCells.Select(cellInfo => cellInfo.Item as MyObjectType)
.Where (myObject => myObject != myViewModel.CurrentItem).Distinct().ToList();
if (wrongObjects.Count > 0)
{
MyDataGrid.UnselectAllCells();
MyDataGrid.SelectedItem = null;
MyDataGrid.SelectedItem = myViewModel.CurrentItem;
}
}
明らかに、ハンドラーは、データ グリッド上の対応するイベントに接続する必要があります。
これは期待どおりに機能し、必要に応じて選択の変更を適切にキャンセルし、ちらつきも発生しませんでした。