Edw*_*uay 4 c# wpf xaml exception
在我的XAML中,我通过绑定到GetAll属性来获取所有客户:
<ListBox ItemsSource="{Binding GetAll}"
ItemTemplate="{StaticResource allCustomersDataTemplate}"
Style="{StaticResource allCustomersListBox}">
</ListBox>
Run Code Online (Sandbox Code Playgroud)
GetAll属性在我的视图模型中是一个可观察的集合,该视图模型调用该模型来获取所有客户集合:
public class CustomersViewModel
{
public ObservableCollection<Customer> GetAll {
get
{
try
{
return Customer.GetAll;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果模型中出现任何问题(格式不正确的XML文件等),则异常会一直冒泡至ViewModel中的该GetAll属性。
第一个问题:XAML似乎对异常没有任何作用,只是继续前进,什么也不显示,我感到很惊讶。这是设计使然吗?这是“脱钩方法”的一部分吗?
第二个问题:这使我认为我可以以某种方式处理XAML中的异常,例如
伪代码:
<Trigger>
<Trigger.OnException>
<TextBox Text="The customer data could not be loaded."/>
</Trigger.OnException>
</Trigger>
Run Code Online (Sandbox Code Playgroud)
上面的代码有可能吗?
首先,我想这不是要捕获XAML异常的意图。尽管它们由于XAML标记的动态性质而必然在运行时(初始化)发生,但它们作为帮助开发人员了解如何修复XAML代码的工具而存在。
这样,您可以通过将调用包装到类InitializeComponents的构造函数中来轻松处理XAML异常Windows。然后,您可以捕获所有异常XamlParseException,也可以捕获特定的异常。
此博客文章中的示例:
public partial class Window1 : System.Windows.Window
{
public Window1()
{
try
{
InitializeComponent();
}
catch (Exception ex)
{
// Log error (including InnerExceptions!)
// Handle exception
}
}
}
Run Code Online (Sandbox Code Playgroud)