I have a ViewModel class which i want to respond to the built in Refresh command whic is fired from a button but i'm not sure how to declare the CommandTarget.
Briefly, my code is as below
The ViewModel constructor and CanExecute and Executed event handlers -
public ViewModel()
{
CommandBinding binding = new CommandBinding(NavigationCommands.Refresh, CommandHandler);
binding.CanExecute += new CanExecuteRoutedEventHandler(binding_CanExecute);
binding.Executed += new ExecutedRoutedEventHandler(binding_Executed);
CommandManager.RegisterClassCommandBinding(typeof(ViewModel), binding);
}
void binding_Executed(object sender, ExecutedRoutedEventArgs e)
{
Debug.Print("Refreshing...");
}
void binding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
The markup is -
<Button Command="Refresh">refresh</Button>
Now, I've tried setting the CommandTarget on this button to {Binding Source={StaticResource ViewModel}}
but i get a runtime saying Cannot convert the value in attribute 'CommandTarget' to object of type 'System.Windows.IInputElement'
.
I'm new to commands so it's entirely possible I'm all kinds of wrong here. Anyhelp would be appreciated.
-
RoutedCommand
s and MVVM do not mix.RoutedCommand
s are tied to the visual tree and to rely on WPF'sCommandBindings
collection. You should implement your ownICommand
classes that work with the MVVM pattern. Take a look at Prism's implementations for starters.In my own MVVM projects, I have a couple of command implementations:
DelegateCommand
. Calls provided delegates to determine whether the command can execute, and to execute the command.ActiveAwareCommand
. Works in conjunction with an interface (IActiveAware
) and sends command executions to the currently active item. Multiple active aware implementations register themselves with the command, and the command automatically routesCanExecute
/Execute
calls to the currently active item.
HTH, Kent
Stimul8d : Thanks Kent. that helps
0 comments:
Post a Comment