我知道之前有人提出这个问题,但我无法找到我要找的东西。
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();
是否有其他方法可以取消selectionchanged事件?
答案 0 :(得分: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);
}
}
}
}
如果用户单击“否”,则成功保持当前行的选择,如果他们单击“是”,则执行将继续正常进行。希望这有助于未来的某些人,因为花了很长时间才找到适合看似简单问题的东西。
答案 1 :(得分:0)
您是否考虑过替代实施?在更改Binding
之前,我正在考虑SelectedItem
和检查方法。举例说明:
<DataGrid ItemsSource="..." SelectedItem="{Binding SelectedEntry}" />
并且底层VM可能如下所示:
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
}
}