Below is a code that does not work. I made it work without validation, I mean I set a criterion inside MyClass‘s set and it did work. However, when I try a validation rule it does not work.
class MyClass
{
private string num;
public string MyString
{
get
{
return num;
}
set
{
num = value;
}
}
}
public class MyValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
float num = System.Convert.ToSingle(value);
// Is positive?
if (num < 0)
{
return new ValidationResult(false, "Must be positive");
}
// Number is valid
return new ValidationResult(true, null);
}
}
public MainWindow()
{
InitializeComponent();
mc = new MyClass();
Binding b = new Binding(mc.MyString);
b.Mode = BindingMode.TwoWay;
b.ValidationRules.Add(new MyValidationRule());
b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
MyTextBox.DataContext = mc;
}
Your binding seems broken. This:
…should be:
Also i do not even see any call to
SetBinding.(How to debug bindings)