How to locate the source of a binding error?

前端 未结 5 448
Happy的楠姐
Happy的楠姐 2020-12-08 05:05

How can I figure out what line of xaml contains the troublesome binding When my debug output is full of lines like the following:

System.Windows.Data Error: 5

5条回答
  •  盖世英雄少女心
    2020-12-08 05:44

    I have been happily using the wonderful snippet from 'Switch on the Code' to detect and report binding errors since it was first published in 2009...

    http://www.switchonthecode.com/tutorials/wpf-snippet-detecting-binding-errors

    edit: still works excellently on VS2012 (Sept 2013)

    Update 25 Jan 2016

    The link appears broken, so I'll paste in the relevant snippets...

    using System.Diagnostics;
    using System.Text;
    using System.Windows;
    
    namespace SOTC_BindingErrorTracer
    {
        public class BindingErrorTraceListener : DefaultTraceListener
        {   //http://www.switchonthecode.com/tutorials/wpf-snippet-detecting-binding-errors
            private static BindingErrorTraceListener _Listener;
            public static void SetTrace()
            { SetTrace(SourceLevels.Error, TraceOptions.None); }
            public static void SetTrace(SourceLevels level, TraceOptions options)
            {
                if (_Listener == null)
                {
                    _Listener = new BindingErrorTraceListener();
                    PresentationTraceSources.DataBindingSource.Listeners.Add(_Listener);
                }
                _Listener.TraceOutputOptions = options;
                PresentationTraceSources.DataBindingSource.Switch.Level = level;
            }
            public static void CloseTrace()
            {
                if (_Listener == null)
                { return; }
                _Listener.Flush();
                _Listener.Close();
                PresentationTraceSources.DataBindingSource.Listeners.Remove(_Listener);
                _Listener = null;
            }
            private StringBuilder _Message = new StringBuilder();
            private BindingErrorTraceListener()
            { }
            public override void Write(string message)
            { _Message.Append(message); }
            public override void WriteLine(string message)
            {
                _Message.Append(message);
    
                var final = _Message.ToString();
                _Message.Length = 0;
    
                MessageBox.Show(final, "Binding Error", MessageBoxButton.OK,
                  MessageBoxImage.Error);
            }
        }
    }
    

    And to set it up/initialize it...

    namespace WpfListeningForTraceErrors
    {
        /// 
        /// Interaction logic for Window1.xaml
        /// 
        public partial class Window1 : Window
        {
            public Window1()
            {
                BindingErrorTraceListener.SetTrace();
                InitializeComponent();
            }
        }
    }
    

提交回复
热议问题