Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I turn binding errors into runtime exceptions?

Just as there is "treat warning as errors" set in our projects to catch early possible problems, I would love to have a runtime exception to catch them early.

I have recently been bit by this problem and I would have been glad to have this.

Can it be done? And if yes, how?

like image 934
Andrei Rînea Avatar asked Nov 19 '10 14:11

Andrei Rînea


2 Answers

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>
like image 177
Dean Chalk Avatar answered Oct 21 '22 12:10

Dean Chalk


I implemented a solution very similar to the one proposed by Dean Chalk:

  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

like image 38
Benoit Blanchon Avatar answered Oct 21 '22 11:10

Benoit Blanchon