[英]validationRule on ObservableCollection
当内容更改时,我需要将ValidationRule应用于ObservableCollection。 该规则只是检查collection.Count> 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();
实际上,更新源确实可以。 我写了一个更简单的测试,它成功了。 我遇到的问题与托管属性的自定义控件有关。 对那些花时间研究此问题的人表示抱歉。
工作解决方案:
myBindingExpression = myListBox.GetBindingExpression(ListBox.ItemsSourceProperty)
collection.CollectionChanged += (sender, args) => myBindingExpression.UpdateSource();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.