PreviewMouseDown方法here有一些示例。
一致意見是在DataGrid的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;
}
}
顯然,處理程序需要連接到數據網格上的相應事件。
這可以像預期的那樣工作,如果需要可以正確取消選擇更改,並且不會產生閃爍。
以前的建議完美運行(雖然後者是一個非常有趣的建議,我也考慮過嘗試) - 謝謝。 – Mani5556