Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
767 views
in Technique[技术] by (71.8m points)

wpf - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...