WPF验证控制

时间:2012-01-13 16:03:40

标签: wpf validation idataerrorinfo validationrules

我是WPF新手并尝试在提交表单上实现验证控件。

任何人都可以帮助我。我的代码不会显示任何错误消息,即使我输入无效数据感染它什么都不做。

这是我的代码,

 public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
}


public class UserName : INotifyPropertyChanged, IDataErrorInfo
{
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, e);
    }

    private string username;
    public string _UserName
    {
        get { return username; }
        set
        {
            username = value;
            OnPropertyChanged(new PropertyChangedEventArgs("_UserName"));
        }
    }
    public string this[string propertyName]
    {
        get
        {
            if (propertyName == "_UserName")
            {
                bool valid = true;
                foreach (char c in _UserName)
                {
                    if (!Char.IsLetterOrDigit(c))
                    {
                        valid = false;
                        break;
                    }
                }
                if (!valid)
                    return "The Username can only contain letters and numbers.";
            }
            return null;
        }
    }
    public string Error
    {
        get { return null; }
    }
}

} 我的XAML代码是,

<Grid>
    <Label Content="User Name" Height="28" HorizontalAlignment="Left" Margin="27,37,0,0" Name="UserNameLB" VerticalAlignment="Top" Width="96" />
    <TextBox Height="23" HorizontalAlignment="Left" Margin="135,37,0,0" Name="UserNameTB" VerticalAlignment="Top" Width="189">
        <TextBox.Text>
            <Binding Path="_UserName">
                <Binding.ValidationRules>
                    <DataErrorValidationRule></DataErrorValidationRule>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>

</Grid>

2 个答案:

答案 0 :(得分:1)

伙计,您所要做的就是将有关验证的所有逻辑放在继承的单独类中 class ValidationRule和ovverride方法Validate。然后,您可以设置要查看的有关验证失败原因的消息,例如

 public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
    try
    {
        if (!Char.IsLetterOrDigit(c))
           return new ValidationResult(false, "The Username can only contain letters 
and numbers.");
    else
    {
        return new ValidationResult(true, null);
    }
    }
    catch (Exception e)
    {
        return new ValidationResult(false, "Illegal characters or " + e.Message);
    }


}

答案 1 :(得分:0)

试试这个:

编辑:(这是我定义的样式,显示所有TextBox控件的错误) (把它放在Window.Resources

此样式将显示 <{1}}

中的错误消息
ToolTip

Source