在設計新的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; }
}
}
}
我更改了代碼以測試數據綁定是否被禁用,但發現它僅顯示無數據(請參閱新代碼)。 正在運行Win7 x64,因此安裝了此修補程序並在系統級別啓用了該修補程序,但未做任何更改。 還有其他想法嗎? – 2010-03-03 01:08:32