Here is the code for demo.
Part 1: Code for MainWindow.xaml(ps: code for the picture which i can't paste here)
<StackPanel>
<Border>
<TextBox x:Name="MaxProficienciesTextBox"
Margin="0,5"
MaxLength="2"
>
<TextBox.Text>
<Binding Path="MaxProficiencies" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<!--<local:MaxProficienciesValidationRule Min="1" SolutionID="{Binding SolutionID}" />-->
<local:MaxProficienciesValidationRule Min="2" SolutionID="0" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</Border>
</StackPanel>
Part 2 : Code for MainWindow.xaml.cs
public partial class MainWindow : Window
{
MyModel myModel = new MyModel();
public MainWindow()
{
InitializeComponent();
this.DataContext = myModel;
}
}
public class MaxProficienciesValidationRule : ValidationRule
{
public long Min { get; set; }
public long SolutionID { get; set; }
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
long proposedMaxProficiencies = 0;
if (SolutionID > 0)
{
return ValidationResult.ValidResult;
}
try
{
if (((string)value).Length > 0)
{
proposedMaxProficiencies = Int64.Parse((string)value);
}
else
{
return new ValidationResult(false, "Empty string invalid");
}
}
catch (Exception ex)
{
return new ValidationResult(false, $"Illegal character(s) or {ex.Message}");
}
if (proposedMaxProficiencies < Min)
{
return new ValidationResult(false, "MaxProficiencies must be greater than 0");
}
return ValidationResult.ValidResult;
}
}
Part 3: Code for MymModel.cs
class MyModel : ViewModeBase
{
private long maxProficiencies;
public long MaxProficiencies
{
get { return maxProficiencies; }
set
{
maxProficiencies = value;
InvokePropertyChanged("MaxProficiencies");
}
}
}
class ViewModeBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void InvokePropertyChanged(string property)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(property));
}
}
}
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.