2013-03-21 76 views
5

我知道這個問題之前被問過,但我找不到我在找什麼。如何在WPF中取消Datagrid selection changed事件?

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; 會選擇DataGrid行。我不想撥打dataGrid1.SelectedIndex =-1;,因爲它會再次觸發selectionchanged事件。我也嘗試dataGrid1.UnSelectAll(); 任何其他方式來取消selectchanged事件?

回答

0

您是否想過替代實現?我正在考慮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 
    } 
} 
+1

您確定這可行嗎?我認爲選擇將會改變,但是SelectedEntry不會 – Demarsch 2014-05-29 07:23:28

1

我用各種方法來嘗試取消選擇更改事件,包括從所選答案的方法,但他們都沒有工作。然而,這對我來說真是棒極了:

使用DataGrid的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); 
      } 
     } 
    } 
} 

這成功地保持如果用戶點擊選擇當前行「否」,如果他們點擊「是「,那麼執行將繼續如常。希望這可以幫助未來的某個人,因爲花費很長時間才能找到能夠解決看似簡單問題的方法。