ObservableCollection上的validationRule

时间:2014-09-19 15:23:58

标签: c# wpf validation binding observablecollection

当内容发生变化时,我需要将一个ValidationRule应用于ObservableCollection。该规则只检查collection.Count> 0

视图模型:

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

1 个答案:

答案 0 :(得分:0)

实际上,更新源代码确实有效。我写了一个更小的测试,它成功了。我遇到的问题与托管该财产的自定义控件有关。对于那些花时间调查这一点的人抱歉。

工作解决方案:

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