Reputation: 844
I have set everything perfectly. If I set some string in ErrorMessage then it shows without error.
What I want is, I want to set ErrorMessage dynamically/programmatically. something
MyValidation.ErrorMessage = "some new message";
username.Update() //something
XAML Code
<TextBox Margin="5" Name="userName">
<TextBox.Text>
<Binding RelativeSource="{RelativeSource Self}" Path="Tag" Mode="OneWayToSource" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:MyValidation ErrorMessage="Static String" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
C# Class Code
public class MyValidation : ValidationRule {
public string ErrorMessage { get; set; }
public override ValidationResult Validate(object value, CultureInfo cultureInfo) {
if (ErrorMessage.Length > 0) {
return new ValidationResult(false, ErrorMessage);
}
return ValidationResult.ValidResult;
}
}
Upvotes: 1
Views: 1671
Reputation: 169160
If you give the ValidationRule
a name in the XAML markup:
<Binding.ValidationRules>
<local:MyValidation x:Name="val" ErrorMessage="Static String" />
</Binding.ValidationRules>
...you could set its ErrorMessage
property directly and then just explicitly update the binding:
val.ErrorMessage = "some new message";
userName.GetBindingExpression(TextBox.TextProperty)?.UpdateSource();
Upvotes: 1
Reputation: 368
You can implement INotifyDataErrorInfo in your viewmodel. Implement GetErrors(string)
so it returns different error messages based on your condition. You can even return multiple messages at once and they will be displayed below each other.
Here's a nice tutorial, but feel free to implement it on your own. Keep in mind that there's not just one correct approach and the interface gives you a lot of freedom.
Upvotes: 1