我的第一个C#WPF ValidationRule没有触发

时间:2013-11-07 13:11:21

标签: c# wpf

我正在尝试学习如何实现数据验证,但我的第一次尝试不是触发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对象非常简单:只有几个属性。

谢谢!

詹姆斯

2 个答案:

答案 0 :(得分:2)

Awww这样一个悲伤的标题:) :)首先,wpf validationrule没有做你想做的事。

每次将输入值(绑定目标属性值)传输到绑定源属性时,绑定引擎都会检查与绑定关联的每个ValidationRule。

记住这一点:

您键入内容并将值保留到source =&gt;验证规则将触发。

您希望在Label中显示某些内容,并且该值正在从源传输到Label =&gt; ValidationRule永远不会开火。

如果你希望你的例子工作,那么取一个TextBox,然后将Binding Mode设置为TwoWay,这样你就可以输入一些内容,Binding会将输入的值保存到源,导致ValidationRule触发。 :)

答案 1 :(得分:0)

我必须这样才能让它为我工作,这是我从this site

获得的
<Binding Path="ID" 
NotifyOnValidationError="True" 
ValidatesOnDataErrors="true" 
ValidatesOnExceptions="True" 
UpdateSourceTrigger="PropertyChanged" Mode="TwoWay">

希望这会有所帮助,同时请注意,object传递给验证的是string,在我的情况下不是int

public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
    if (value is int)
    {
        int iValue = (int)value;
        if (iValue == 0) 
        {
            return new ValidationResult(false, "No ID number");
        }

        return new ValidationResult(true, null);
    }
    else if (value is string)
    { 
        string strValue = (string)value;
        if (String.IsNullOrEmpty(strValue) || strValue == "0")
        { 
            return new ValidationResult(false, "No ID number"); 
        }
    }

    return new ValidationResult(true, null);
}

*更新**

我忘了我还必须添加它才能触发

public wValidationRule()
{
    InitializeComponent();
    cus.ID = 0;
    stkMain.DataContext = cus;

    //trigger the validation.
    lblSource.GetBindingExpression(Label.ContentProperty).UpdateSource();
}
相关问题