How can I turn binding errors into runtime exceptions?

You could hook into the PresentationTraceSources collection with your own listener:

public class BindingErrorListener : TraceListener
{
    private Action<string> logAction;
    public static void Listen(Action<string> logAction)
    {
        PresentationTraceSources.DataBindingSource.Listeners
            .Add(new BindingErrorListener() { logAction = logAction });
    }
    public override void Write(string message) { }
    public override void WriteLine(string message)
    {
        logAction(message);
    }
}

and then hook it up in code-behind

public partial class MainWindow : Window
{
    public MainWindow()
    {
        BindingErrorListener.Listen(m => MessageBox.Show(m));
        InitializeComponent();
        DataContext = new string[] { "hello" };
    }
}

Here is the XAML with a binding error

    <Grid>
    <TextBlock Text="{Binding BadBinding}" />
</Grid>

Leave a Comment