I'm working on a C# project in WPF.
In my main windows I have 5 (maybe more late) TextBox
, each box contains a float
with a value between 0 and 100.
I've created a validation rule :
class RangeValidationRule : ValidationRule
{
public float MinValue { get; set; }
public float MaxValue { get; set; }
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
float intValue;
string text = String.Format("Must be between {0} and {1}",
MinValue, MaxValue);
if (!float.TryParse(value.ToString(), out intValue))
return new ValidationResult(false, "Not a float");
if (intValue < MinValue)
return new ValidationResult(false, "To small. " + text);
if (intValue > MaxValue)
return new ValidationResult(false, "To large. " + text);
return ValidationResult.ValidResult;
}
}
But I don't know how to simplify the using of it. Actually I use it like this :
<TextBox Grid.Row="3" Grid.Column="1"
Style="{StaticResource StyleTextBox}">
<TextBox.Text>
<Binding Path="ValueToBind" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:RangeValidationRule MinValue="0" MaxValue="100"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
How can I simplify my code ? Can I create a style for this type of TextBox ?
<Style x:Key="StyleTextBox0To100" TargetType="TextBox"
BasedOn="{StaticResource StyleTextBox}">
<!-- What should I write ? -->
</Style>
The solution you are searching is BindingGroup
Previously asked question