我有這三個屬性一個ViewModel:應該在哪裏「調用命令屬性更改」功能去?
string searchString;
ObservableCollection<Company> ListedItems;
ICommand SearchCommand;
它代表公司的在我的數據庫搜索列表。 SearchCommand
根據searchString
的值搜索數據庫,然後用結果填充ListedItems
。
SearchString
綁定到文本框,而SearchCommand
綁定到按鈕。我想這樣做,當用戶鍵入文本框時,SearchCommand
會自動執行,用戶不必點擊按鈕。
此刻,我通過我的ViewModel做到這一點:
public ListViewModel() {
this.PropertyChanged += delegate(object o, PropertyChangedEventArgs e)
{
if (e.PropertyName == "SearchString")
SearchCommand.Execute(null);
};
}
這是正確的嗎?在視圖中使用這個功能會更好嗎?如果是這樣,那是如何實現的?
掛鉤到PropertyChanged更方便,因爲它只發生在屬性更改(而不是設置爲相同的值)時也在真實viewModel中有幾個不同的字符串屬性被搜索。 – Oliver
@Oliver在setter中,你可以做'if(myProperty == value){return; }'。這樣,你避免了「設置爲相同的值」(並且在我看來,當值沒有改變時,你不應該觸發任何propertyChanged事件) – Default