For the problem of validating the bound data, you could refer to the following code.
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
public double DiceThreshold { get;set;}= 0.3;
public MainWindow()
{
InitializeComponent();
DataContext=this;
}
}
public class DoubleRangeRule : ValidationRule
{
public double Min { get; set; }
public double Max { get; set; }
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
double parameter = 0;
try
{
if (((string)value).Length > 0)
{
parameter = Double.Parse((String)value);
}
}
catch (Exception e)
{
return new ValidationResult(false, "Illegal characters or " + e.Message);
}
if ((parameter < this.Min) || (parameter > this.Max))
{
return new ValidationResult(false,
"Please enter value in the range: "
+ this.Min + " - " + this.Max + ".");
}
return new ValidationResult(true, null);
}
}
MainWindow.xaml:
<Window.Resources>
<local:DoubleRangeRule x:Key="DoubleRangeRule"/>
<Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)/ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
<ControlTemplate x:Key="validationTemplate">
<DockPanel>
<TextBlock Foreground="Red" FontSize="20">!</TextBlock>
<AdornedElementPlaceholder/>
</DockPanel>
</ControlTemplate>
</Window.Resources>
<Grid>
<TextBox x:Name="DiceTol" Background="Wheat" Width="100" Height="46" Validation.ErrorTemplate="{StaticResource validationTemplate}" Style="{StaticResource textBoxInError}">
<TextBox.Text>
<Binding Path="DiceThreshold" StringFormat="N2" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:DoubleRangeRule Min="0.0" Max="1.0"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</Grid>
The result:
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.