Introduction
If you want to create some WPF control which
allows users to input emails like it is in Gmail client, then here it is. You can
find the control implementation in MultiSelectTextBox.xaml file in the source. Here I will describe it shortly (shortly -
because I believe all you need to understand how it works is in the source).
This
control works like gmail or yandex email input control in browser clients:
- The list of available Emails can be found by clicking on "^" button to the right of opened window. Email could be chosen by double clicking on it or using Enter key.
- To add new email, you should set the cursor into the blank place, type Email and hit Enter key. If email is incorrect, you'll get error message and input field will be highlighted with red canvas.
- As you type email, you'll see the listbox with email automatically filtered.
- Already selected emails will be hidden in dropdown listbox, so you'll not be able to choose them twice. To delete selected email, you should press Back button, or click red cross near email address.
- All new email addresses will be added to global list (in
listbox
), but you
can only see them if they are not present in selected emails list above.
Using the Code
Control
uses standard WPF validation features such as Binding.ValidationRules
:
<TextBox.Text>
<Binding Path="Email" NotifyOnValidationError="True">
<Binding.ValidationRules>
<ExceptionValidationRule/>
<local:EmailValidationRule></local:EmailValidationRule>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
And
on the CS side:
public class EmailValidationRule : ValidationRule
{
public EmailValidationRule()
{
}
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
string Text = value as string;
if (Text != null && Text.Length>0
&& !Regex.IsMatch((string)value,
@"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"))
{
return new ValidationResult(false, "Incorrect email format");
}
else
{
return new ValidationResult(true, null);
}
}
}
And inside MultiSelectTextBox
class:
#region Validation members
public string Email
{
get;
set;
}
private void validationError(object sender, ValidationErrorEventArgs e)
{
if (!m_popup.IsOpen &&e.Action == ValidationErrorEventAction.Added)
{
MessageBox.Show(e.Error.ErrorContent.ToString());
}
}
#endregion
Points of Interest
I was asked to create this control as a test of my skils before the final interview. The control is working and can be a good start for those who want to learn WPF.