[英]How can I make Prism's DelegateCommand observe a child view-model's property?
[英]DelegateCommand in Prism whose canExecuteMethod is determined by a property in an ObservableCollection. How do I continue to “Observe” canExecute?
我有一個可實現BindableBase
和IDataErrorInfo
的類的可觀察的集合。 在我看來,我有一個按鈕,其ICommand
綁定僅在可觀察集合中的每個元素都經過驗證時才可以執行。 由於其中一個元素幾乎總是會開始無效,因此該按鈕最初被禁用。 我的構造函數中包含以下代碼:
this.StartInspectionCommand = new DelegateCommand(this.StartInspection, () => this.Parameters.All(p => string.IsNullOrEmpty(p["Value"])))
我的可觀察集合的定義如下:
public ObservableCollection<Parameter> Parameters { get; } = new ObservableCollection<Parameter>();
我的Paramters類中的IDataErrorInfo
的實現是這樣的:
public string this[string columnName]
{
get
{
if (columnName != "Value" // Only validate value column
|| string.IsNullOrEmpty(this._validationExpression) // No validation means all values including null are valid
|| (this.Value != null && Regex.IsMatch(this.Value, this._validationExpression))) // No null allowed when validating
{
return ""; // No error
}
return this._validationMessage;
}
}
當用戶在各種參數中輸入有效值時,要重新評估canExecuteMethod的語法是什么? (或者,就此而言,導致當前有效的無效。)
我知道如何對屬性本身使用ObservesCanExecute
和ObservesProperty<T>
,但是我不確定如何將其應用於ObservableCollection
的類中的屬性。
謝謝。
在這種情況下,您不要使用ObservesProperty或ObservesCanExcute。 更新集合中的屬性后,必須手動調用StartInspectionCommand.RaiseCanExecuteChanged。
除了@Brian Lagunas的答案之外,您還可以處理Parameters
集合中所有項目的PropertyChanged
事件,並在RaiseCanExecuteChanged
任何項目的屬性時調用RaiseCanExecuteChanged
方法,例如:
public class ViewModel
{
public ViewModel()
{
this.StartInspectionCommand = new DelegateCommand(this.StartInspection, () => this.Parameters.All(p => string.IsNullOrEmpty(p["Value"])))
this.Parameters.CollectionChanged += Parameters_CollectionChanged;
}
public ObservableCollection<Parameter> Parameters { get; } = new ObservableCollection<Parameter>();
private void Parameters_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (object parameter in e.NewItems)
{
(parameter as INotifyPropertyChanged).PropertyChanged
+= new PropertyChangedEventHandler(item_PropertyChanged);
}
}
if (e.OldItems != null)
{
foreach (object parameter in e.OldItems)
{
(parameter as INotifyPropertyChanged).PropertyChanged
-= new PropertyChangedEventHandler(item_PropertyChanged);
}
}
}
private void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
StartInspectionCommand.RaiseCanExecuteChanged();
}
//...
}
如果有任何掘墓者仍在尋找該問題的答案,我已經找到了解決此問題的另一種方法,因為我無法使ObservableCollection觸發CollectionChanged事件。
填充集合后,我手動進行迭代並設置每個項目的屬性更改,如下所示:
OrdersToConfirm = new ObservableCollection<mConfirmedQuote>(_quoteService.GetOrdersToBeConfirmed());
OrdersToConfirm.ToList().ForEach(x => { x.PropertyChanged += item_PropertyChanged; });
private void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
ConfirmCommand.RaiseCanExecuteChanged();
}
我不確定這樣做有什么弊端,如果有的話會有所更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.