Reputation: 8448
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
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
Reputation: 18168
Upvotes: 1