简体   繁体   English

ObservableCollection上的validationRule

[英]validationRule on ObservableCollection

I need to apply a ValidationRule to an ObservableCollection when it's contents change. 当内容更改时,我需要将ValidationRule应用于ObservableCollection。 The rule simply checks if the collection.Count > 0. 该规则只是检查collection.Count> 0。

ViewModel: ViewModel:

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

Generic view example: 通用视图示例:

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

I can't seem to get the validationRule to be fired when the contents change. 当内容更改时,似乎无法触发validationRule。 I've even tried listening to CollectionChanged and making calls directly on the BindingExpression and the ValidationRule itself, but didn't yield results yet. 我什至尝试听CollectionChanged并直接在BindingExpression和ValidationRule本身上进行调用,但尚未产生结果。 The event is hit, but the calls on the binding/rule do not execute the validation sequence. 事件已命中,但是绑定/规则上的调用未执行验证序列。

//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();

Actually, updating the source does work. 实际上,更新源确实可以。 I wrote a more minimal test and it succeeded. 我写了一个更简单的测试,它成功了。 The problem i'm having has to do with the custom control that's hosting the property. 我遇到的问题与托管属性的自定义控件有关。 Sorry for those that spent any time investigating this. 对那些花时间研究此问题的人表示抱歉。

working solution: 工作解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM