我試圖創建一個綁定到按鈕的命令,並且依賴於viewmodels的層次結構來表示wp7應用程序中的樞軸和pivotitems。它是這樣的(我會忽略儘可能多的樣板代碼可能):RelayCommand not firing CanExecute
父視圖模型:
public RelayCommand RefreshCommand
{
get
{
return _refreshCommand;
}
set
{
if (_refreshCommand == value)
{
return;
}
var oldValue = _refreshCommand;
_refreshCommand = value;
// Update bindings, no broadcast
RaisePropertyChanged(RefreshCommandPropertyName);
}
}
public RelayCommand<RoutedEventArgs> LoadedCommand
{
get
{
Action<RoutedEventArgs> getCurrentViewmodel = (args) =>
{
CurrentViewModel = SearchByLocationViewModel; // maybe something better...
RefreshCommand = CurrentViewModel.RefreshResultsCommand;
RefreshCommand.RaiseCanExecuteChanged();
};
return new RelayCommand<RoutedEventArgs>(getCurrentViewmodel);
}
}
public RelayCommand<SelectionChangedEventArgs> PivotItemChangedCommand
{
get
{
Action<SelectionChangedEventArgs> pivotChanged = (args) =>
{
if (args != null)
{
// update current viewmodel
CurrentViewModel = ((Microsoft.Phone.Controls.PivotItem) args.AddedItems[0]).DataContext as ISearchViewModelBase;
RefreshCommand = CurrentViewModel.RefreshResultsCommand;
}
};
return new RelayCommand<SelectionChangedEventArgs>(pivotChanged);
}
}
所以,我父視圖模型RefreshCommand屬性設置爲每次子命令它會加載,而且我在選定的透視圖變化時也會這樣做。
的XAML
<Button Command="{Binding RefreshCommand}" />
子視圖模型
public Func<bool> CanRefresh
{
get { return() => !IsLoading; }
}
private RelayCommand refreshResultsCommand;
public RelayCommand RefreshResultsCommand
{
get
{
Action doRefresh =() =>
{
SearchResults.Clear();
this._pageNumber = 0;
AddItems();
};
return refreshResultsCommand = refreshResultsCommand ?? new RelayCommand(doRefresh, CanRefresh);
}
}
會發生什麼情況是,該CanRefresh永遠不會被調用。這些命令可以正常工作,具體取決於它調用一個AddItems(這是在每個子視圖模型中實現的虛擬方法)或另一個,但它就像CanExecute永遠不會引發。我正在使用MVVM Light工具包。 謝謝!
當你說'CanRefresh從不叫'時,你的意思是'CanRefresh'屬性還是其中的lambda?你怎麼知道它從來沒有被稱爲? – 2012-02-18 18:01:22