【问题标题】:Dispatcher throws InvalidOperationException on Messagebox.Show in Textchanged eventDispatcher 在 Textchanged 事件中的 Messagebox.Show 上引发 InvalidOperationException
【发布时间】:2011-11-18 13:36:57
【问题描述】:

首先这是关于我的错误的错误日志条目

crash program @ 15-9-2011 15:01:30error:System.InvalidOperationException: Dispatcher processing has been suspended, but messages are still being processed. at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

无论如何代码:

private void TB_postcode_cijfers_TextChanged(object sender, TextChangedEventArgs e){
if (TB_postcode_cijfers.Text != string.Empty || TB_postcode_cijfers.Text.Length > 0)
{
    LBL_postcode.Content = Postcode_cijfers + Postcode_letters;
    if (TB_postcode_cijfers.Text.Length == 4 && TB_postcode_letters.Text.Length == 2)
    {
        if (!ZoekOpPostcode(Injectioncheck(TB_postcode_cijfers.Text + TB_postcode_letters.Text)))
        {
            //MessageBox.Show("Geen resultaat gevonden, " + errortext);
            if (MessageBox.Show("Geen resultaat gevonden, " + errortext + ".\n Wilt u overschakelen naar handmatig? ", "Handmatig?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                RB_handmatig.IsChecked = true;
            }
            else
            {
                //
            }
        }
    }
}}

所以在 messagebox.show 方法上。 这只发生在用户在我的表单上将阅读模式切换到编辑模式时。 这涉及折叠并显示一些标签和 ui 控件。

如果事件从用户输入触发,一切都很好。 我想知道的: 为什么在隐藏和显示一些控件时会触发 textchanged 事件。 我能做些什么来防止这个错误?

编辑: 上面的代码在自定义 wpf 控件中。放在一个winforms项目/表单中

【问题讨论】:

  • 您的 MessageBox 代码是否在 UI 线程上运行?
  • 不确定,据我所知,因为它应该是来自 ui 控件的事件?对吗??
  • 是否可以在 MessageBox.Show() 中提供所有者窗口?它有一个接受窗口所有者的重载签名。
  • 它在一个自定义控件中,我在一些(旧)winforms 和其他(新)wpf 窗口中使用......但我会检查我是否可以让它工作
  • 我可以提供表格但不能提供窗口......

标签: c# wpf custom-controls


【解决方案1】:

看到这个thread它描述了和你一样的问题:

该异常是为了防止由以下原因引起的可重入错误 改变视觉树导致的怪异,而这样的事件 (其本身已由视觉树更改触发)是 射击。如果你真的必须确认某事时的状态 UI 元素发生变化,延迟 Dispatcher.BeginInvoke 可能是 做正确的事。

要在 UI 线程上运行代码,请执行以下操作:

 Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() =>
     {

        if (MessageBox.Show("Geen resultaat gevonden, " + errortext + ".\n Wilt u overschakelen naar handmatig? ", "Handmatig?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
        {
            RB_handmatig.IsChecked = true;
        }
        else
        {
            //
        }
    }));

【讨论】:

  • 不太了解 lambda,但这给了我错误 Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type
  • 现在构建,但在第一行给出 NullReferenceException。我开始怀疑那个时候调度员还活着?
  • Oke 调试告诉我 Application.Current = null 这怎么可能..
  • 不知道为什么会这样,这是WPF项目吗?否则,您可以使用附加到每个控件的调度程序,例如 RB_handmatig.Dispatcher.BeginInvoke()。调用语法略有不同,但我相信您会找到有关它的示例
  • 它实际上是一个winforms项目。但是因为在切换到 wpf 的地方,我把这个控件 (wpf) 放在了一个 winforms 表单上。我会把它放在问题中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多