gpt4 book ai didi

WPF DataTemplate 不抛出异常

转载 作者:行者123 更新时间:2023-12-02 02:34:34 28 4
gpt4 key购买 nike

在设计新的 WPF 应用程序时,我注意到在使用 DataTemplates 对控件进行数据绑定(bind)期间不会抛出异常。为了测试,我用尽可能少的逻辑编写了以下简单的用户控件。我正在使用在 WIN7 上运行的 .NET 3.5 SP1、VS2008 SP1。

设置 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; }
}
}
}

最佳答案

数据绑定(bind)抛出的异常被转换为跟踪,被传送到 DataBindingSource TraceSource,其源名称为“System.Windows.Data”。

您可以通过创建在跟踪上抛出异常的 TraceListner 的子类将它们转换为异常,并将其添加到 TraceSourceSource 的 Listeners 集合中。这可以在代码中或在您的 App.config 文件中完成。

以下是您在代码中的做法:

System.Diagnostics.PresentationTraceSources.DataBindingSource.Listeners.Add(
new MyTraceListener());

有关详细信息,请参阅 TraceSource 和 TraceListener 文档和示例。

关于WPF DataTemplate 不抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2357046/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com