Có một số ví dụ cho phương pháp PreviewMouseDown here.
Thỏa thuận chung là đảo ngược DataGrid.SelectedItem về giá trị ban đầu của nó bên trong trình xử lý SelectionChanged của datagrid không hoạt động như mong đợi; tất cả các ví dụ mã dường như làm việc trì hoãn việc đảo ngược bằng cách yêu cầu Dispatcher lên lịch cho nó sau này.
Bạn có CellStyle trên DataGrid của mình không? Đối với tôi, sau đây làm việc:
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>
codebehind:
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;
}
}
}
Điểm là trường hợp SelectedCellsChanged sa thải sau sự kiện SelectionChanged - và đặc biệt, đó là thiết lập SelectedItem không cập nhật chính xác SelectedCells là thuộc tính chỉ đọc, do đó, thêm codebehind:
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;
}
}
Rõ ràng, các trình xử lý cần phải được nối với các sự kiện tương ứng trên lưới dữ liệu.
Điều này hoạt động như mong đợi, đã hủy đúng thay đổi lựa chọn nếu muốn và không tạo ra nhấp nháy.
Nguồn
2013-09-24 04:55:06
Đề xuất trước đây hoạt động hoàn hảo (mặc dù đề xuất sau đây là một đề xuất rất thú vị và tôi cũng đã cân nhắc dùng thử) - Cảm ơn bạn. – Mani5556