从 .NET3.5 到 .NET4.0,我遇到了一个非常烦人的变化。 在绑定(bind)上使用 ExceptionValidationRule 来验证绑定(bind)属性 setter 中抛出的异常时,由 3.5 中的绑定(bind)处理。在 4.0 中,它在调试时被视为未处理。
在这个小示例(新的 WPF 应用程序项目)中将目标框架从 3.5 更改为 >4.0 显示了问题:
主窗口.xaml.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
private string _field = "Test";
public string Property
{
get { return _field; }
set
{
if (value.Length < 4)
_field = value;
else
throw new ArgumentException();
}
}
}
主窗口.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Height="350"
Width="525">
<TextBox Width="300"
Height="100"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Text="{Binding Property, ValidatesOnExceptions=True, UpdateSourceTrigger=PropertyChanged}" />
</Window>
在 .NET4.0 中是否可以在调试时处理这些异常?
最佳答案
您应该改用 IDataErrorInfo
和 ValidatesOnDataErrors
。您不仅不会遇到这些情况,而且还避免了在堆栈中冒泡异常的实际性能损失。
关于c# - 与 ValidatesOnException 绑定(bind)会在 .Net4 中引发未处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3805607/