Проверка связывания без XAML - PullRequest
0 голосов
/ 30 августа 2011

Мой вопрос: как мы можем написать код C # вместо 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 #, чтобы текстовое поле использовало проверку привязки?

1 Ответ

2 голосов
/ 30 августа 2011

Просто добавить новое правило?

bindtext.ValidationRules.Add(new NumberRangeRule() { Min = 0, Max = 128 });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...