8

我知道以前有人问过这个问题,但我找不到我要找的东西。

    private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

if (oOrdItem.ItemNo == 0)
                {
                    e.Handled = true;
                    MessageBox.Show("Please save the order item", "Save");
                    return;
                }
}

即使我调用e.Handled = true; 它也会选择数据网格行。我不想打电话dataGrid1.SelectedIndex =-1;,因为它会再次触发 selectionchanged 事件。我也尝试过dataGrid1.UnSelectAll(); 任何其他方式来取消 selectionchanged 事件?

4

2 回答 2

6

我使用了多种方法来尝试取消选择更改事件,包括选择答案中的方法,但都没有奏效。然而,这对我很有用:

使用数据网格的 PreviewMouseDown 事件处理程序:

private void dataGrid_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    //get the item I am clicking on (replace MyDataClass with datatype in datagrid)
    var myItem = (e.OriginalSource as FrameworkElement).DataContext as MyDataClass;

    //check if item is different from currently selected item
    if (myItem != dataGrid.SelectedItem)
    {
         //save message dialog
         MessageBoxResult result = MessageBox.Show("Changes will be lost. Are you sure?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question);

         //if click no, then cancel the event
         if (result == MessageBoxResult.No)
         {
             e.Handled = true;
         }
         else
         {
           //otherwise, reinvoke the click event
           dataGrid.Dispatcher.BeginInvoke(
              new Action(() =>
              {
                 RoutedEventArgs args = new MouseButtonEventArgs(e.MouseDevice, 0, e.ChangedButton);
                 args.RoutedEvent = UIElement.MouseDownEvent;
                 (e.OriginalSource as UIElement).RaiseEvent(args);
              }),
              System.Windows.Threading.DispatcherPriority.Input);
           }
        }
    }
}

如果用户单击“否”,这将成功保持当前行被选中,如果他们单击“是”,则执行将照常继续。希望这对将来的某人有所帮助,因为花了很长时间才找到可以解决看似简单的问题的方法。

于 2017-10-25T17:11:03.170 回答
-1

您是否考虑过另一种实现方式?在Binding更改SelectedItem. 插图:

<DataGrid ItemsSource="..." SelectedItem="{Binding SelectedEntry}" />

底层虚拟机可能如下所示:

public class SampleVm : ViewModelBase//assuming that you are using such a base class
{
   private object _selectedEntry;
   public object SelectedEntry
   {
       get { return _selectedEntry; }
       set 
       {
           if (!SavePrevItem())
               return;

           _selectedEntry = value;
           RaisePropertyChanged("SelectedItem"); // or something similar
       }
   }

   private bool SavePrevItem()
   {
       // your logic here
   }
}
于 2013-03-21T11:24:27.570 回答