I’m new to WPF so I’m not sure if what I’m doing makes any sense.. anyway: I’m trying to implement a command for a button that uses ApplicationCommands.Open.
In my XAML I have:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ViewModel"
Title="MainWindow" Height="650" Width="1170">
<Window.DataContext>
<local:ResourceListViewModel/>
</Window.DataContext>
I want to have a command definition in a local:ResourceListViewModel class, so so far I got there:
void OpenCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
MessageBox.Show("The command has been invoked");
}
void OpenCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
So what I think I must do is to bind these methods to a command, so I’m trying to do it this way:
<Window.CommandBindings >
<CommandBinding Command="ApplicationCommands.Open"
Executed="OpenCmdExecuted"
CanExecute="OpenCmdCanExecute"/>
</Window.CommandBindings>
but the program is not compiling as it seems to be looking for these functions in MainWindow. How can I let the program know that my functions’ definitions are in a different class?
That’s not the way Commands work in MVVM. There is a difference between
RoutedCommands (such asApplicationCommands.Open, andDelegateCommands (a.k.aRelayCommands).The first are View-related and bubble up the visual tree, etc, and have to be handled by the View in code-behind.
The second are ViewModel-related and are defined in the ViewModel (meaning the Command instance is a property member of the ViewModel itself)