I'm trying to create a command that binds to a button, and depends on a hierarchy of viewmodels to represent a pivot and pivotitems in a wp7 app. It goes something like this (i'll omit as much boilerplate code as possible):
Parent viewmodel :
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);
}
}
So, i'm setting the parent view model's RefreshCommand property to the child command each time it loads, and I do the same when the selected pivotitem changes.
Xaml
<Button Command="{Binding RefreshCommand}" />
Child viewmodel
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);
}
}
What happens is, the CanRefresh is NEVER called. The commands work fine, depending on the pivotitem it calls one AddItems (that's a virtual method implemented differently in each child viewmodel) or the other, but it's like CanExecute is never raised. I'm using MVVM Light toolkit. Thanks!
CanRefreshproperty, or the lambda within it? How can you tell that it is never called? - Luke Woodward