Dispatcher在Textchanged事件中的Messagebox.Show上抛出InvalidOperationException

Daa*_*nvl 12 c# wpf custom-controls

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

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
            {
                //
            }
        }
    }
}}
Run Code Online (Sandbox Code Playgroud)

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

如果事件从userinput触发,一切都很好.我想知道的是:为什么隐藏和显示一些控件时,textchanged事件会触发.我该怎么做才能防止这个错误?

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

thu*_*eys 22

看到这个线程,它描述了与你相同的问题:

例外是为了防止由于改变视觉树而导致的奇怪性引起的重入错误,而这种事件(它本身已由视觉树改变触发)被触发.如果你真的必须在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
        {
            //
        }
    }));
Run Code Online (Sandbox Code Playgroud)