Exception handling in WPF data binding

Let's say I have the following code in WPF application:

try
{
   // NorthwindDataContext is LINQ DataContext created for SQL Server Northwind database
   Data.NorthwindDataContext data = new Data.NorthwindDataContext(connectionString);

   var orders = from order in Data.Orders select order;

   listView.DataContext = orders;
}
catch (SqlException ex)
{
   MessageBox.Show(ex.Message);
}

If connectionString is incorrect, this code doesn't throw SqlException immediately. Instead of this, exception is thrown later, when WPF data binding starts to enumerate LINQ query. Application crashes with unhandled exception. How can I handle exception in such situation?

I know that it is possible with global exception handling, but I want more precise way, which allows to catch specific exception when specific function is executed.


This is the curse of the Linq and not data binding.

Your query has been compiled but not run - you are binding to a query not the result. Change to the following code:

var orders = from order in Data.Orders select order;
var realOrders = orders.ToList();
listView.DataContext = realOrders ;

Basically your repository must always return results and not raw queries.

链接地址: http://www.djcxy.com/p/51230.html

上一篇: 奇怪的未经处理的WPF异常

下一篇: WPF数据绑定中的异常处理