PreviewMouseDownメソッドhereのいくつかの例があります。
DataGrid.SelectedItemをDataGridのSelectionChangedハンドラ内の元の値に戻すことは、期待通りに機能しません。 Dispatcherに後でスケジューリングを依頼することによって、逆転を延期するように思われるすべてのコード例があります。
DataGridに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;
}
}
明らかに、ハンドラはデータグリッドの対応するイベントに接続する必要があります。
これは期待どおりに機能し、必要に応じて選択の変更を適切にキャンセルし、フリッカーを生成しませんでした。
前の提案は完全に機能しました(後者は非常に興味深い提案ですが、試してみることも考えました)。ありがとうございます。 – Mani5556