How to propagate errors & exceptions that occur during WPF data binding?

后端 未结 4 1036
半阙折子戏
半阙折子戏 2020-12-25 08:43

Every so often I find that I have accidentally broken data binding in my application. Either by renaming a property and not renaming it in the XAML or by a property throwin

相关标签:
4条回答
  • 2020-12-25 08:58

    Have a look at this blog article which may help get around this issue.

    0 讨论(0)
  • 2020-12-25 09:04

    After some procrastination I finally set about coding a solution to my original issue.

    My solution uses a custom TraceListener (originally suggested by John) that logs to an output window. The output window is automatically displayed and bought to the foreground when an error occurs.

    Here is my TraceListener:

    public class ErrorLogTraceListener : TraceListener
    {
        public override void Write(string message)
        {
            ...
        }
    
        public override void WriteLine(string message)
        {
            ...
        }
    }
    

    TraceListener is defined in System.Diagnostics.

    The custom TraceListener must be hooked into the system to be used. The official way to do this is to set something in the registry and then use the App.config file to configure the TraceListener.

    However I found that there is a much easier way to do this programmatically:

    ErrorLogTraceListener listener = new ErrorLogTraceListener();
    PresentationTraceSources.Refresh();
    
    PresentationTraceSources.DataBindingSource.Listeners.Add(listener);
    PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.Error;
    

    PresentationTraceSources is also defined in System.Diagnostics.

    For more information on trace sources see Mike Hillberg's blog.

    Bea Stollnitz has some useful info on her blog.

    0 讨论(0)
  • 2020-12-25 09:16

    Raising binding exceptions in WPF & Silverlight with .net 4.0 Dynamics.

    0 讨论(0)
  • 2020-12-25 09:18

    I implemented a solution very similar to the accepted answer:

    1. Derived a TraceListener that throws instead of logging
    2. Added that listener to PresentationTraceSources.DataBindingSource

    Please see the complete solution on GitHub, it includes a demo application and a unit test project.

    Exception in Visual Studio

    0 讨论(0)
提交回复
热议问题