我可以处理XAML抛出的异常? [英] Can I handle thrown exceptions in XAML?

查看:168
本文介绍了我可以处理XAML抛出的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的XAML我通过结合GETALL属性来获取所有客户:

In my XAML I get all customers by binding to a GetAll property:

<ListBox ItemsSource="{Binding GetAll}" 
     ItemTemplate="{StaticResource allCustomersDataTemplate}"
     Style="{StaticResource allCustomersListBox}">
</ListBox>



GETALL属性是我的视图模型,它调用模型得到的所有集合中观察的集合客户:

The GetAll property is an observable collection in my view model, which calls the Model to get all collection of customers:

public class CustomersViewModel
{
    public ObservableCollection<Customer> GetAll {
        get
        {
            try
            {
                return Customer.GetAll;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
}

如果任何错误模型(错误的XML文件等),那么一个异常冒泡一路在视图模型的GETALL财产。

If anything goes wrong in the model (badly formed XML file, etc.) then an exception bubbles up all the way to that GetAll property in the ViewModel.

第一个问题:我很惊讶, XAML似乎并不唯独做任何事情,只是继续运行并显示任何内容。这是设计?是脱钩办法

First Question: I was surprised that XAML doesn't seem to do anything with the exception and just goes ahead and displays nothing. Is this by design? Is this part of the "decoupling approach"?

第二个问题的这部分:这使我想到的我可以处理除了在XAML莫名其妙,如

Second Question: This leads me to think I could handle the exception in XAML somehow, such as

伪代码:

<Trigger>
    <Trigger.OnException>
        <TextBox Text="The customer data could not be loaded."/>
    </Trigger.OnException>
</Trigger>



是一样的东西,上面的代码可能吗?

Is something like the above code possible?

推荐答案

首先,我会想象,这并不意味着XAML异常应该被捕获。它们的存在更作为一种工具来帮助开发人员了解它们如何需要解决他们的XAML代码,尽管他们有因为XAML标记

Firstly, I would imagine that it is not intended that XAML exceptions should be caught. They exist more as a tool to help the developer see how they need to fix their XAML code, though they have to of course occur at runtime (initialisation) because of the dynamic nature of XAML markup

话说,你可以通过你的窗口的构造函数中包装调用 InitializeComponents 类。然后,您可以捕获所有异常或特别 XamlParseException ,无论你觉得不合适。

Saying that, you can handle XAML exceptions quite easily by wrapping the call to InitializeComponents within the constructor of your Windows class. You can then either catch all exceptions or specifically XamlParseException, whichever you find appropiate.

从的这个博客帖子

public partial class Window1 : System.Windows.Window 
{
    public Window1()
    {
        try
        {
            InitializeComponent();
        }
        catch (Exception ex)
        {
            // Log error (including InnerExceptions!)
            // Handle exception
        }
    }
}

这篇关于我可以处理XAML抛出的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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