简体   繁体   中英

validationRule on ObservableCollection

I need to apply a ValidationRule to an ObservableCollection when it's contents change. The rule simply checks if the collection.Count > 0.

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. I've even tried listening to CollectionChanged and making calls directly on the BindingExpression and the ValidationRule itself, but didn't yield results yet. 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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