我正在尝试学习如何实现数据验证,但我的第一次尝试不是触发 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 对象非常简单:只有几个属性。
Thanks!
James
啊,真是一个悲伤的标题:) :) 首先 wpfvalidationrule 没有做你想做的事。
每次将输入值(绑定目标属性值)传输到绑定源属性时,绑定引擎都会检查与绑定关联的每个 ValidationRule。
记住这一点:
您输入一些内容,该值将被保存到源 => ValidationRule 将触发。
您想在标签中显示某些内容,并且该值正在从源传输到标签=> ValidationRule 永远不会触发。
如果您希望示例正常工作,请改为使用 TextBox,并将 Binding Mode 设置为 TwoWay,以便您可以输入某些内容,Binding 会将输入的值保留到源中,从而导致 ValidationRule 触发。 :)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)