I create an int ValidationRule demo due to having no relevant information about decimal points with ValidationRule
, below is my sample code:
Xaml code:
<Window.DataContext>
<local:ViewModel></local:ViewModel>
</Window.DataContext>
<Window.Resources>
<local:MyConverter x:Key="MyConver"></local:MyConverter>
</Window.Resources>
<Grid>
<TextBox Name="TextBox1" Width="50" Margin="0,0,10,0" Height="21" FontSize="12" ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" >
<TextBox.Text>
<Binding Path="SetTemperature" UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<local:AgeRangeRule Min="21" Max="130"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<Button Content="Button" Width="120" Height="50" VerticalAlignment="Top" IsEnabled="{Binding ElementName=TextBox1,Path=(Validation.HasError),Converter={StaticResource MyConver}}"></Button>
</Grid>
C# code:
public class AgeRangeRule : ValidationRule
{
public int Min { get; set; }
public int Max { get; set; }
public AgeRangeRule()
{
}
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
int age = 0;
try
{
if (((string)value).Length > 0)
age = Int32.Parse((String)value);
}
catch (Exception e)
{
return new ValidationResult(false, $"Illegal characters or {e.Message}");
}
if ((age < Min) || (age > Max))
{
return new ValidationResult(false,
$"Please enter an age in the range: {Min}-{Max}.");
}
return ValidationResult.ValidResult;
}
}
public class ViewModel
{
public int SetTemperature { get; set; }
public ViewModel()
{
SetTemperature = 50;
}
}
public class MyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool flag = (bool)value;
flag = !flag;
return flag;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
The result picture is:
If my answer didn't give you help, please show your rest of code which related to Button
for me to make a demo to reproduce your error.
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.