I'm new in WPF/XAML and I need help. I didn't found a response to my question in the existing questions/answers or I failed in using them. I have a wpf application with several textboxes, checkboxes and comboboxes : all are binded to properties of my Object. I have also a cancel and a validate buttons. To not update the properties bind to my textboxes (and etc...), I used UpdateSourceTrigger ="Explicit". I would like to use a ValidationRule when Focus is lost on my email address text box but I don't know how to do.
My XAML is :
<TextBox Margin="5 0 5 0" x:Name="txtBox_mailSender"
Validation.ErrorTemplate="{StaticResource ValidationTemplate}">
<TextBox.Text>
<Binding Path="SenderMailAddress"
UpdateSourceTrigger="Explicit">
<Binding.ValidationRules>
<local:EmailAddressValidator />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
My EmailAddressValidator :
public class EmailAddressValidator : ValidationRule
{
//public override ValidationResult Validate(object value, CultureInfo cultureInfo)
//{
// Regex mailAddressRegex = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
// @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
// @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
// if(!mailAddressRegex.IsMatch((string)value))
// {
// return new ValidationResult(false, $"Adresse E-mail invalide.");
// }
// return new ValidationResult(true, null);
//}
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
try
{
new MailAddress(value.ToString());
}
catch (Exception)
{
return new ValidationResult(false, "Adresse E-mail invalide.");
}
return new ValidationResult(true, null);
}
}
My Control Template (Validation Template) but I think it's not necessary since the red border is good for me :
<ControlTemplate x:Key="ValidationTemplate">
<DockPanel>
<TextBlock Foreground="Red" >!</TextBlock>
<AdornedElementPlaceholder/>
</DockPanel>
</ControlTemplate>
I tried with the LostFocus event but I don't know how to transform the textbox into a "textbox with errors".
An extract of my object with the e-mail property :
public class MyObject
{
public String SenderMailAddress
{
set
{
if (SenderMailAddress != value)
{
_senderMailAddress = value;
OnSpecificModification();
}
}
get
{
return _senderMailAddress;
}
}
private String _senderMailAddress = "";
}
Thank you for your help.
IEditableObject
in your view model and changeUpdateSourceTrigger
toPropertyChanged
. – mm8