validationRule on ObservableCollection

本文关键字:ObservableCollection on validationRule | 更新日期: 2023-09-27 18:23:40

当ObservableCollection的内容发生变化时,我需要将ValidationRule应用于它。该规则只是检查集合是否为。计数>0。

ViewModel:

private ObservableCollection<string> _items;
public ObservableCollection<string> Items
{
  get { return _items; }
  set { _items = value; OnPropertyChanged("Items"); }
}

通用视图示例:

  <ListBox>
    <ListBox.ItemsSource>
      <Binding Path="Items" ValidatesOnDataErrors="True">
        <Binding.ValidationRules>
          <a:ValidationRule />
        </Binding.ValidationRules>
      </Binding>
    </ListBox.ItemsSource>
  </ListBox>

当内容发生更改时,我似乎无法启动validationRule。我甚至尝试过监听CollectionChanged,并直接对BindingExpression和ValidationRule本身进行调用,但还没有产生结果。事件被命中,但对绑定/规则的调用不执行验证序列。

//runs the validation, but it does not update the HasError property (appears to just run validation outside of the binding's context
collection.CollectionChanged += (sender, args) => myValidationRule.Validate(collection, CultureInfo.CurrentCulture);
//doesn't execute the validation rule.. works for regular bindings - just not ObservableCollection bindings
collection.CollectionChanged += (sender, args) => myBindingExpression.UpdateSource();

validationRule on ObservableCollection

实际上,更新源代码确实有效。我写了一个更简单的测试,它成功了。我遇到的问题与托管该属性的自定义控件有关。很抱歉那些花时间调查此事的人。

工作解决方案:

myBindingExpression = myListBox.GetBindingExpression(ListBox.ItemsSourceProperty)
collection.CollectionChanged += (sender, args) => myBindingExpression.UpdateSource();