【发布时间】:2020-04-01 05:54:57
【问题描述】:
我有一个非常简单的课程,我们称之为客户。 它看起来像这样:
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.");
}
}
}
}
}
现在,我创建了一个基本表单,用户可以在其中将客户添加到数据库中。该表单包含简单的 TextBox,绑定到 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 中的验证的好文章(例如 Enforcing Complex Business Data Rules with WPF、Data validation in WPF 和 Windows Presentation Foundation 中的验证),但没有一篇能帮助我解决我的问题。
最后,我希望表单看起来像第一个链接上的 Brian Noyes 优秀文章中的表单(没有 10 个学分,所以我不能附上照片……抱歉)。
如果有人能向我解释它是如何工作的,我将不胜感激。
重要提示 - 我正在使用 .Net 框架 4,因此我需要一个适合此版本的解决方案。
【问题讨论】:
标签: c# wpf validation xaml