0
我的問題是,我們如何可以寫C#代碼替換爲XAML綁定驗證? 例如XAML綁定驗證沒有XAML
<TextBox.Text>
<Binding Path="Age" UpdateSourceTrigger="PropertyChanged">
<!--<Binding Path="Age" NotifyOnValidationError="True">-->
<Binding.ValidationRules>
<!--<ExceptionValidationRule />-->
**<local:NumberRangeRule Min="0" Max="128" />**
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
如果在C#代碼
Binding bindtext = new Binding();
Person person = new Person("Tom",12);
bindtext.Source = person;
bindtext.Mode = BindingMode.TwoWay;
bindtext.Path = new PropertyPath("Age");
bindtext.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
bindtext.ValidatesOnExceptions = true;
ageTextBox.SetBinding(TextBox.TextProperty, bindtext);
////////////////////////// //
用戶定義驗證類
public class NumberRangeRule : ValidationRule {
int _min;
public int Min {
get { return _min; }
set { _min = value; }
}
int _max;
public int Max {
get { return _max; }
set { _max = value; }
}
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) {
int number;
if(!int.TryParse((string)value, out number)) {
return new ValidationResult(false, "Invalid number format");
}
if(number < _min || number > _max) {
string s = string.Format("Number out of range ({0}-{1})", _min, _max);
return new ValidationResult(false, s);
}
//return new ValidationResult(true, null);
return ValidationResult.ValidResult;
}
}
////////////////////////////////
但我們怎麼能寫驗證規則在C#,使文本框使用綁定驗證?
O,謝謝。有用。 – flyKite
@ user838053:高興的是幫助,您可以[接受](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)我的答案通過點擊左邊的複選標記輪廓。 –