gpt4 book ai didi

c# - DataGridRow出错时阻塞所有控件

转载 作者:太空宇宙 更新时间:2023-11-03 13:58:32 24 4
gpt4 key购买 nike

我正在处理一个 WPF 项目,现在我正在验证 DataGrid 中的数据。因此,当插入无效数据时,我会在 RowHeader 中显示通知图像。到目前为止一切顺利。

但我的问题是:有没有办法在插入“无效”数据时阻止应用程序中的任何其他控件,除了 DataGrid 的当前行?或者,在输入正确的数据之前,我该怎么做才能防止当前行失去焦点??

到目前为止,我的想法是使用 eventAggregator 引发一个事件,以将错误通知所有控件。但这很难,因为我必须在我可能拥有的每个控件中使用一个方法。

希望有人能帮助我,在此先感谢您。

最佳答案

通过取消 CellEditEnding 事件,您可以阻止单元格失去焦点:

public MainWindow()
{
InitializeComponent();

dataGrid1.ItemsSource = new List<TestClass>() { new TestClass() };
dataGrid1.CellEditEnding += new EventHandler<DataGridCellEditEndingEventArgs>(dataGrid1_CellEditEnding);
}

void dataGrid1_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
if(whateveryouwant == true)
return;
else
e.Cancel = true;
}

编辑:

EventAggregator 是解决它的好方法,但由于您知道但似乎不喜欢它,所以下面是一种更简单的方法,尽管您必须指定一些应该能够停止的控件类型:

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

dataGrid1.ItemsSource = new List<TestClass>() { new TestClass() };
dataGrid1.CellEditEnding += new EventHandler<DataGridCellEditEndingEventArgs>(dataGrid1_CellEditEnding);

MouseDownHandler = new MouseButtonEventHandler((sender, args) => { args.Handled = true; });
MouseClickHandler = new RoutedEventHandler((sender, args) => { args.Handled = true; });
}

private bool IsMouseEventStopped = false;
private RoutedEventHandler MouseClickHandler = null;
private MouseButtonEventHandler MouseDownHandler = null;

void dataGrid1_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
bool correctCellValue = false;

//correctCellValue = true to stop editing, if the cell value is correct


if (correctCellValue)
{
// unblock mouse events
if (IsMouseEventStopped == true)
{
foreach (Button c in FindVisualChildren<Button>(this))
c.Click -= MouseClickHandler;
foreach (TextBox c in FindVisualChildren<TextBox>(this))
c.PreviewMouseLeftButtonDown -= MouseDownHandler;
}
IsMouseEventStopped = false;
}
else
{
e.Cancel = true;
// block mouse events to certain controls
if (IsMouseEventStopped == false)
{
IsMouseEventStopped = true;
foreach (Button c in FindVisualChildren<Button>(this))
c.Click += MouseClickHandler;
foreach (TextBox c in FindVisualChildren<TextBox>(this))
c.PreviewMouseLeftButtonDown += MouseDownHandler;
}
}
}

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
yield return (T)child;

foreach (T childOfChild in FindVisualChildren<T>(child))
yield return childOfChild;
}
}
}
}

感谢 Bryce Kahle 的 FindVisualChildren from here

关于c# - DataGridRow出错时阻塞所有控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11378882/

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