gpt4 book ai didi

c# - 调用 MessageBox.Show() 时抛出 "An ItemsControl is inconsistent with its items source"

转载 作者:太空宇宙 更新时间:2023-11-03 23:26:45 26 4
gpt4 key购买 nike

我是 WPF 的新手,我遇到了以下问题:

我正在尝试开发一个练习应用程序来帮助我控制预算。

我有一个像这样的 Partida 类:

public class Partida
{
public delegate void PartidaChangedHandler(Partida p);
public event PartidaChangedHandler OnPartidaChanged;
private ObservableCollection<PartidaEntry> content;

public Partida()
{
content = new ObservableCollection<PartidaEntry>();
content.CollectionChanged += PartidaEntriesCollectionChanged;

}

public void PartidaEntriesCollectionChanged(object s, NotifyCollectionChangedEventArgs args)
{
if (OnPartidaChanged != null)
{
OnPartidaChanged(this);
}
}
}

我正在使用 Datagrid 显示 content 集合,但我需要知道此类的 content 集合何时更改并触发 OnPartidaChanged 事件。

在类之外(在 MainWindow 中)我连接到 OnPartidaChanged 事件,如下所示:

p.OnPartidaChanged += (Partida ppp) =>
{
int foo = 5;
MessageBox.Show("A partida has changed!");
};

当我在 DataGrid 中添加一个新行时,事件会正确触发,但是一旦 MessageBox 被执行,我就会收到一个包含以下消息的 InvalidOperationException:

An ItemsControl is inconsistent with its items source.

知道如何在不失去监听 ObservableCollection 的 CollectionChanged 事件并在该事件后触发 OnPartidaChanged 的​​能力的情况下解决该问题吗?

提前致谢!

P.S.:此外,我想知道 MessageBox 与 ItemControl 到底有什么关系...如果 MessageBox 仅显示一个简单的框,为什么会触发异常! :S

最佳答案

WPF add item to datagrid bound to observablecollection exception中的答案清楚地解释了正在发生的事情:在更改集合的操作正在进行时调用事件处理程序,调用 MessageBox.Show() 为调度程序消息处理循环提供了启动的机会再次处理消息。这会导致与 WPF 工作方式不兼容的重入:集合更改操作尚未完全解决,但 UI 有机会尝试运行不应运行的逻辑,直到<之后 该操作已完全解决。

换句话说,就像异常状态一样,控件处于不一致状态,因为它被允许做一些本不应该发生的处理,直到它完全完成对集合更改的处理。

我承认其他答案中的建议并不是很有说服力。就目前而言,这是合理的建议,但没有提供真正的替代方案。

在您的场景中,在不更改您的实现的任何其他内容的情况下,一个明显的解决方案是将消息框推迟到集合更改操作完全解决之后。为此,您可以使用 Dispatcher.InvokeAsync() 方法来推迟对 MessageBox.Show() 的调用的执行:

p.OnPartidaChanged += (Partida ppp) =>
{
int foo = 5;
Dispatcher.InvokeAsync(() => MessageBox.Show("A partida has changed!"));
};

当然,还有一个问题是显示消息框是否真的是处理事件的最佳方式。从您问题中的有限信息来看,您的事件处理程序为何看起来像这样并不清楚。如果您确定每次集合更改时显示消息框确实是正确的做法,那么上述内容应该可以解决您的问题。

但是您可能需要考虑向用户呈现信息的其他方式,例如在 UI 的状态字段中显示信息,或者甚至提供某种事件日志,例如在多行文本框或列表框中。这些类型的方法通常涉及适合 WPF 中事件和数据处理的正常流程的数据绑定(bind),并且可以作为同步代码工作,而不会遇到您在此处看到的问题。

关于c# - 调用 MessageBox.Show() 时抛出 "An ItemsControl is inconsistent with its items source",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33586333/

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