簡體   English   中英

ObservableCollection上的validationRule

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM