c# - 我可以在 XAML 中处理抛出的异常吗?

标签 c# wpf exception xaml

在我的 XAML 中,我通过绑定(bind)到 GetAll 属性来获取所有客户:

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

GetAll 属性是我的 View 模型中的一个可观察集合,它调用模型来获取所有客户集合:

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

如果模型中出现任何错误(格式错误的 XML 文件等),则异常会一直冒泡到 ViewModel 中的 GetAll 属性。

第一个问题:令我感到惊讶的是,XAML 似乎没有对异常执行任何操作,只是继续进行,什么也不显示。这是设计使然吗?这是“解耦方法”的一部分吗?

第二个问题:这让我想到我可以以某种方式处理 XAML 中的异常,例如

伪代码:

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

上面的代码是否可行?

最佳答案

首先,我认为应该捕获 XAML 异常并不是故意的。它们更多地作为一种工具存在,以帮助开发人员了解他们需要如何修复 XAML 代码,尽管由于 XAML 标记的动态特性,它们当然必须在运行时(初始化)出现

也就是说,通过将对 InitializeComponents 的调用包装在 Windows 类的构造函数中,您可以非常轻松地处理 XAML 异常。然后,您可以捕获所有异常或特定 XamlParseException,以您认为合适的为准。

示例来自 this blog post :

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

关于c# - 我可以在 XAML 中处理抛出的异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/823929/

相关文章:

java - 当方法抛出异常时,Netbeans 不强制我 try catch

c# - 当 Enum 在 ViewModel 中时将 Enum 值作为 CommandParameter 传递

c# - SqlDataReader 返回 null

c# - 从配置中读取定时器触发计划

c# - 可以在 View 中显示 RelayCommand 吗?

c# - CefSharp.wpf Web 浏览器导航事件 (C# .Net)

c++ - 我可以让 Visual Studio 中断用户定义的 C++ 异常吗?

c# - 使用 Entity Framework 加载嵌套实体/集合

c# - 如何访问 WPF Xaml 中的控件引用?

java - 如果用户使用键盘输入错误,如何再次调用该类