E
E
Ethiopian2014-08-04 11:34:48
WPF
Ethiopian, 2014-08-04 11:34:48

WPF "swallows" exceptions. Where to dig?

Greetings. We encountered a problem in the project: there is a WinForms frame on which a WPF control is added to ElementHost:

var child = new SomeWPFControl();
var host = new ElementHost
                {
                    Child = child,
                    Dock = DockStyle.Fill
                };
 Controls.Add(host);

It works great, but the trouble is that if an exception occurs inside the control, then it is simply swallowed and nothing comes up. In the control itself, I would not want to block try / catch blocks, because the project has a global exception handling with a dialog box for the user. Google brought up the advice to add an exception event handler to the control itself, when adding it to the frame and in it already betray it further:
child.Dispatcher.UnhandledException += DispatcherUnhandledException;

private void DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            //Вместо окна планировалось пробросить исключение дальше, 
            //но до этого обработчика событие не добирается.
            MessageBox.Show("Произошло необработанное исключение: " + e.Exception.Message, "Exception");
            e.Handled = true;
        }

There is no effect, exceptions do not reach this handler.
App.xaml.cs has a global handler that doesn't catch these exceptions either:
Application.Current.DispatcherUnhandledException +=  handleUIThreadException;

Has anyone experienced this behavior? Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Ethiopian, 2014-08-06
@Ethiopian

Temporarily solved the problem as follows:

// Создаем класс, который будет слушать отладочную информацию
 public class BindingErrorListener : TraceListener
    {
        public BindingErrorListener()
        {
            // Ловим только ошибки
            PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.Error;
            this.Filter = new SourceFilter("System.Windows.Data");
        }

        // Этот метод вызываем при инициализации окна, чтобы начать слушать поток
        public static void Listen()
        {
            PresentationTraceSources.DataBindingSource.Listeners.Add(new BindingErrorListener());
        }
        public override void Write(string message) { }

        // Этот метод вызывается при попытке вывести в отладчик сообщение об ошибке привязки
        public override void WriteLine(string message)
        {
                // Бросаем ислючение с информацией об ошибке
                throw new Exception(message);
        }
    }

If anyone has a more elegant solution, we'd be very happy to see it.

S
Sumor, 2014-08-04
@Sumor

Binding errors are swallowed - this is really a feature of WPF. They are written to the debugger output with a description of the error.
To catch errors, you can use the BindingComplete event, approximately as described by Microsoft.
An example of catching Binding errors.
In addition, there is an interesting mechanism for checking ValidationRule values.
ValidationRule example

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question