0

I'm working on trying to implement validation in WPF, and running into an issue where I can't click on or change the value of a textbox after validation fails.

I have a User class (which implements IDataErrorInfo), which contains the following relevant code:

public virtual string Error
{
    get
    {
        return null;
    }
}

public virtual string this[string name]
{
    get
    {
        string result = null;

        if (name == "uFirstName")
        {
           if (String.IsNullOrEmpty(this.uFirstName))
            {
                return "Must enter a first name!";
            }
         }
         return result;
     }
}

Then, over in my MainWindow code-behind, I have this code to hookup my combobox:

comboBox1.ItemsSource = Users; //Users is a collection of Users

Finally, in my MainWindow xaml, I have this:

<ComboBox Name="comboBox1" ItemTemplate="{StaticResource userTemplate}" />
<TextBox Name="textBox1" DataContext="{Binding ElementName=comboBox1,
    Path=SelectedItem}" Text="{Binding Path=uFirstName, ValidatesOnDataErrors=True,
    NotifyOnValidationError=True}"/>

And indeed, the validation does fire when I delete the text and the textbox gets a nice red border. However, the changes are still sent back to Users (uFirstName gets set to nothing!). Even worse though, I now cannot edit the value in that textbox unless I tab back into it.

What is needed to make sure the value isn't sent back if it isn't valid, and allow the textbox to be edited if is invalid?

4

1 回答 1

0

IDataErrorInfo 实现仅用于报告错误。您应该在 uFirstName 属性中实现您的验证。如果您认为某个属性的某个验证并非对所有实例都是正确的,那么您应该开始研究ValidationRule. 这是在 WPF 中实现验证的更好方法。如果验证失败,ValidationRule 不会为源设置值。

由于系统级别的样式,文本框可能表现得很奇怪?不完全确定您在那里遇到麻烦的原因。

于 2012-08-16T02:11:46.537 回答