我有一个非常简单的课程,我们称之为“客户”。
它看起来像这样:
namespace TestValidation
{
class Customer
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
if (String.IsNullOrEmpty(value))
{
throw new Exception("Customer name is mandatory.");
}
}
}
}
}
现在,我创建了一个基本表单,用户可以在其中将客户添加到数据库中。该表单包含简单的文本框(绑定到 Customer 的 Name 属性)和一个“添加”按钮。
XAML代码是:
<Window x:Class="TestValidation.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestValidation"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox Margin="119,86,107,194" Name="CustomerName"
Text="{Binding Path=Customer.Name,
ValidatesOnExceptions=True,
ValidatesOnDataErrors=True,
UpdateSourceTrigger=PropertyChanged,
NotifyOnValidationError=True}"
/>
<Button Content="Add" HorizontalAlignment="Left" Margin="204,176,0,0" VerticalAlignment="Top" Width="74"/>
</Grid>
</Window>
从 Name 属性的设置器中,您可以了解到该名称对我来说是必需的,因此我希望如果 Name TextBox 留空,则会引发验证事件。根据 WPF 的验证规则 - 一旦用户将焦点移出文本框,并且那里没有值 - 它应该将边框颜色更改为红色。由于某种原因 - 这没有发生,我不知道为什么。我的流程出了什么问题?
现在,我已经阅读了很多关于 WPF 中的验证的好文章(例如使用 WPF 实施复杂的业务数据规则 http://msdn.microsoft.com/en-us/magazine/ff714593.aspx, WPF 中的数据验证 http://blog.magnusmontin.net/2013/08/26/data-validation-in-wpf/和 Windows Presentation Foundation 中的验证),但它们都没有帮助我解决我的问题。
最终,我希望该表格看起来像 Brian Noyes 优秀文章中第一个链接中的表格(没有 10 个学分,所以我无法附上照片......抱歉)。
如果有人能向我解释它是如何工作的,我将不胜感激。
重要说明 - 我正在使用 .Net Framework 4,因此我需要一个适合该版本的解决方案。