WPF DataTemplate不抛出异常
问题描述:
在设计新的WPF应用程序时,我注意到在DataTemplates控件的数据绑定期间没有引发异常。为了测试,我用尽可能少的逻辑写了下面的简单用户控件。我正在使用WIN7上运行的.NET 3.5 SP1,VS2008 SP1。WPF DataTemplate不抛出异常
当设置DataContext时,将调用TestMethod并在代码隐藏中抛出异常,但应用程序不会中断。
有人会介意解释创建DataTemplate时发生了什么吗?具体而言,我对例外情况感兴趣。
下面是XAML代码:
<UserControl x:Class="WPF2008.DataTemplateQuestion"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<UserControl.Resources>
<DataTemplate x:Key="TESTKey">
<Border BorderBrush="Black" BorderThickness="10">
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<TextBox Grid.Row="0" Text="{Binding Path=Txt}" />
<TextBox Grid.Row="1" Text="{Binding Path=Lbl}" />
<TextBox Grid.Row="2" Text="Am I disabled?" />
<TextBox Grid.Row="3" Text="I am disabled." IsEnabled="False" />
</Grid>
</Border>
</DataTemplate>
</UserControl.Resources>
<Grid>
<Label x:Name="lblTest" Content="{Binding Path=TestMethod}" ContentTemplate="{StaticResource TESTKey}" />
</Grid>
</UserControl>
下面的代码隐藏:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WPF2008
{
public partial class DataTemplateQuestion : UserControl
{
public DataTemplateQuestion()
{
try
{
InitializeComponent();
lblTest.DataContext = new TestClass();
}
catch (Exception e)
{
// ADDING A BREAKPOINT HERE DOESN'T CATCH THE EXCEPTION
throw e;
}
}
}
public class TestClass
{
public TestValue TestMethod
{
get
{
// BREAKPOINT WILL BE HIT WHEN DEBUGGING BUT THE EXCEPTION DISAPPEARS
throw new Exception("WATCH ME DISAPPEAR");
return new TestValue { Lbl = "Label", Txt = "Text" };
}
}
public class TestValue
{
public string Lbl { get; set; }
public string Txt { get; set; }
}
}
}
答
由数据绑定抛出的异常会被转换为跟踪,这些异常将传递到DataBindingSource
TraceSource
,该源的名称为“System.Windows.Data”。
您可以通过创建的TraceListner
一个子类,抛出一个跟踪异常转换到这些异常,并把它添加到Listeners
收集TraceSourceSource
的。这可以通过代码或在App.config
文件中完成。
这里是你会怎么做代码:
System.Diagnostics.PresentationTraceSources.DataBindingSource.Listeners.Add(
new MyTraceListener());
见TraceSource和TraceListener的文档和示例的更多细节。
答
例外得到通过数据绑定吃掉,导致数据绑定被禁用(我不是100 %肯定是这种情况,我懒得把它放进VS)。
另一种可能性是,如果您运行的是64位操作系统,则可能会遇到http://support.microsoft.com/kb/976038。
我更改了代码以测试数据绑定是否被禁用,但发现它仅显示无数据(请参阅新代码)。 正在运行Win7 x64,因此安装了此修补程序并在系统级别启用了该修补程序,但未做任何更改。 还有其他想法吗? – 2010-03-03 01:08:32