如何将绑定错误转换为运行时异常? [英] How can I turn binding errors into runtime exceptions?

查看:153
本文介绍了如何将绑定错误转换为运行时异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如在我们的项目中设置处理警告为错误以捕获早期可能的问题一样,我希望有一个运行时异常可以及早捕获它们。

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?

推荐答案

你可以挂钩 PresentationTraceSources 收藏与您自己的监听器:

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);
    }
}

然后将其挂接在代码隐藏中p>

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" };
    }
}

这是具有绑定错误的XAML

Here is the XAML with a binding error

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

这篇关于如何将绑定错误转换为运行时异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆