Sonhja
Sonhja

Reputation: 8448

WPF validation not working as expected

I have a TextBox on WPF that I want to validate. I'm using Binding to validate it:

<TextBox Text="{Binding Path=Name, UpdateSourceTrigger=Explicit}" TabIndex="0" LostFocus="TextBox_OnLostFocus">
</TextBox>

The LostFocus event:

private void TextBox_OnLostFocus(object sender, RoutedEventArgs e)
{
    ((Control) sender).GetBindingExpression(TextBox.TextProperty);
}

Code behind the validation:

public string Name
{
    get { return _name; }
    set
    {
        _name = value;
        this.OnPropertyChanged(new PropertyChangedEventArgs("Name"));

    }
}

public string Error { get { return this[null]; } }

public string this[string columnName]
{
    get
    {
        string result = string.Empty;
        columnName = columnName ?? string.Empty;
        if (columnName == string.Empty || columnName == "Name")
        {
            if (string.IsNullOrEmpty(this.Name))
            {
                result += Properties.Resources.ValidationName + Environment.NewLine;
            }
        }
        return result.TrimEnd();
    }
}

I have some questions:

1. When I first load my Window, my control is surrounded by a red square (the validation one), but I want it to appear only when I fire it (on the Explicit side).

2. How can I know if all my fields have been validated? I mean, when I press a button I only need to know how to know if all controls have been validated.

NOTE: I do have this context on the Constructor:

User u = new User();
DataContext = u;

Upvotes: 0

Views: 697

Answers (2)

Sonhja
Sonhja

Reputation: 8448

Actually, my problem had something to do with the class I used to validate. The class does this:

public ErrorProvider()
{
    this.DataContextChanged += new DependencyPropertyChangedEventHandler(ErrorProvider_DataContextChanged);
    this.Loaded += new RoutedEventHandler(ErrorProvider_Loaded);
}

So whenever it first loads, it suscribes to the Load event and then it launches this:

private void ErrorProvider_Loaded(object sender, RoutedEventArgs e)
{
    Validate();
}

so I commented it, and launched the Validate() method when needed....

Upvotes: 0

Szymon Rozga
Szymon Rozga

Reputation: 18168

  1. Your first question may be answered here Did you try setting the binding mode to Default?
  2. The Validation.HasError Attached Property will tell you if any binding on a particular UI Element has any binding validation errors. Use that on every control you need to have validated. Try that first. If you are using a pattern like MVVM, you could create properties on your VM to bind to the Validation.HasError properties.

Upvotes: 1

Related Questions