gpt4 book ai didi

wpf - 如何在 WPF 中取消 Datagrid 选择更改事件?

转载 作者:行者123 更新时间:2023-12-04 12:22:36 25 4
gpt4 key购买 nike

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

    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 事件吗?

最佳答案

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

为数据网格使用 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);
}
}
}
}

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

关于wpf - 如何在 WPF 中取消 Datagrid 选择更改事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15545736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com