我用各種方法來嘗試取消選擇更改事件,包括從所選答案的方法,但他們都沒有工作。然而,這對我來說真是棒極了:
使用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);
}
}
}
}
這成功地保持如果用戶點擊選擇當前行「否」,如果他們點擊「是「,那麼執行將繼續如常。希望這可以幫助未來的某個人,因爲花費很長時間才能找到能夠解決看似簡單問題的方法。
您確定這可行嗎?我認爲選擇將會改變,但是SelectedEntry不會 – Demarsch 2014-05-29 07:23:28