I am having difficulty in getting the desired outcome when using a regex through WPF to limit what characters can be typed into a textbox. Currently I have a fairly standard Xaml textbox...
<TextBox x:Name="txtRegistration"
Text="{Binding Registration,UpdateSourceTrigger=PropertyChanged}"
IsEnabled="{Binding RegistrationIsEnabled}"
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Left"
Height="Auto"
Width="Auto"
VerticalAlignment="Center"/>
...which is bound to this property in the viewmodel...
private string _registration;
public string Registration
{
get { return _registration; }
set
{
if (System.Text.RegularExpressions.Regex.IsMatch(value, "[^0-9]", System.Text.RegularExpressions.RegexOptions.Singleline))
{
}
else
{
_registration = value;
}
RaisePropertyChanged("Registration");
}
}
I should point out that my viewmodel implements MVVMLight's version of ViewModelBase.
What I'm expecting to happen here:
if the user types a numeric character, the
regex.IsMatch
function won't find a conflicting character and therefore jump to the else statement where the field will be updated with the value as normal and passed back to the textbox.if the user types a non-numeric character, the
regex.IsMatch
function will find a conflicting character and therefore not update the field with the new value. The textbox will be updated with the value that was held for the property before the user tried to enter a non numeric character, therefore effectively stopping them typing non numeric characters
When I breakpoint on the setter the process seems to work as I described above except the actual value shown in the textbox doesn't reflect this (e.g typing "123abc" into the textbox shows "123abc" instead of just "123")
I'm not entirely sure where the problem is here, so any suggestions would be much appreciated.
Also, I should point out I am not looking for a solution where the validation is done in the Xaml as I need it to be done in the view model for providing different options for the regex based on custom settings for different clients.
Thanks!