I have a WPF window with some ComboBox
and TextBox
controls in it. I populate the comboboxes upon initialization, and the textboxes have two-way bindings to some properties in my viewmodel.
I had this idea to randomize the selected indices of my comboboxes and the text in the text boxes in my window's code-behind upon clicking a button, just to see if my implementation and validation logic were sound, but using this method it's very tedious and error-prone to repeatedly set focus to each text box to trigger their validations. The textboxes hold values of double
, so using UpdateSourceTrigger="PropertyChanged"
doesn't allow manual input of the decimal symbol (point or comma or what have you) and I feel like both input methods should be supported.
Example xaml
code:
<TextBox x:Name="DataValueBox" Grid.Row="3" Grid.Column="3" Height="auto" VerticalAlignment="Center" Margin="10 0">
<TextBox.Text>
<Binding ElementName="DataComboBox"
Path="SelectedItem.Value"
Mode="TwoWay"
ValidatesOnExceptions="True"
NotifyOnValidationError="True"
UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<validators:DoubleRule />
</Binding.ValidationRules>
<Binding.Converter>
<converters:StringToDoubleConverter />
</Binding.Converter>
</Binding>
</TextBox.Text>
</TextBox>
String to double converter (happens after validation):
public class StringToDoubleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
=> value.ToString();
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> double.Parse(value.ToString(), NumberStyles.Float, CultureInfo.CurrentCulture);
}
String validation (checks if a string represents a double
in the current culture):
public class DoubleRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
string valueString = value.ToString();
NumberStyles style = NumberStyles.Float;
CultureInfo culture = CultureInfo.CurrentCulture;
double _ = 0.0;
// Initial parse attempt
bool parsed = double.TryParse(valueString, style, culture, out _);
return parsed ? ValidationResult.ValidResult : new ValidationResult(false, "Please input a valid decimal number.");
}
}
Is there a way to trigger a textbox's validation sequence when I change its text from the code-behind, or is there a better way to provide randomized data that will trigger validations?