我正在尝试学习如何实现数据验证,但我的第一次尝试不是触发 lblSource_Error 事件;有谁知道我错过了什么?
我的窗口的 XAML:
<Window x:Class="cCompleteWPFResourcesExamples.wValidationRule"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:cCompleteWPFResourcesExamples"
Title="wValidationRule" Height="300" Width="300">
<Window.Resources>
<local:Customer x:Key="rCustomer" Forename="InXaml" Surname="Created" ID="1"
AmountOutstanding="0"/>
</Window.Resources>
<StackPanel x:Name="stkMain" DataContext="{StaticResource rCustomer}">
<Label x:Name="lblSource" Validation.Error="lblSource_Error">
<Label.Content>
<Binding Path="ID" NotifyOnValidationError="True">
<Binding.ValidationRules>
<local:cIDValidationRule/>
</Binding.ValidationRules>
</Binding>
</Label.Content>
</Label>
<Label x:Name="lblErrorMessage" Content="No Error Yet"/>
</StackPanel>
</Window>
我的窗口代码:
namespace cCompleteWPFResourcesExamples
{
/// <summary>
/// Interaction logic for wValidationRule.xaml
/// </summary>
public partial class wValidationRule : Window
{
Customer cus = new Customer();
public wValidationRule()
{
InitializeComponent();
cus.ID = 0;
stkMain.DataContext = cus;
}
private void lblSource_Error(object sender, ValidationErrorEventArgs e)
{
lblErrorMessage.Content = e.Error.ErrorContent.ToString();
}
}
}
我的验证规则:
using System.Windows.Controls;
namespace cCompleteWPFResourcesExamples
{
public class cIDValidationRule : ValidationRule
{
public override ValidationResult Validate(object value,
System.Globalization.CultureInfo cultureInfo)
{
int iValue = (int)value;
if (iValue == 0) return new ValidationResult(false, "No ID number");
return new ValidationResult(true, null);
}
}
}
Customer 对象非常简单:只有几个属性。
谢谢!
詹姆士