Reputation: 4889
I need a few answers here as can't seem to find much online which are answering my questions. From my understanding, to follow the MVVM workflow when coding an WPF application, the data, logic and user input needs to be separate.
So, to follow that logic i'm guessing I would create a folder called something like Classes
, then create a class file called Commands.cs
.
Commands.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Duplicate_Deleter.Classes
{
class WindowCommands
{
}
class DatabaseCommands
{
}
class OtherCommands
{
}
}
Then I have got to reference this class file within my XAML so my user input window knows what the command is right?
<Window
xmlns:local="clr-namespace:Classes.Commands">
</Window>
Then of course I would setup the commands so it knows which method to use for each state, e.g:
<Window.CommandBindings>
<CommandBinding Command="WindowCommands.WindowClose" Executed="CloseWindow_Executed" CanExecute="CloseWindow_CanExecute" />
<CommandBinding Command="WindowMinimize" Executed="CloseWindow_Executed" CanExecute="CloseWindow_CanExecute" />
</Window.CommandBindings>
Am I thinking right here? Could someone clarify this or explain how to do what i'm attempting if i'm doing it wrong?
Upvotes: 1
Views: 1315
Reputation: 4913
Martyn,
Let's make things clear.
Commands are an important part of MVVM.
But most of the time Commands (implementers of ICommand) are properties of the ViewModel object.
public class MyViewModel{
public ICommand SaveCmd { get; set; }
}
CommandSources like Buttons and MenuItems bind to Commands :
<Button Command="{Binding SaveCmd}" Content="Save" />
ICommmand contains two methods :
Commands are on the ViewModel side so they can easily adapt the data for the view, be disabled if the data is not correct for the Command to be executed.
All what you're showing : CommandBindings, is interesting but more rarely used.
With CommandBindings you can attach code on the GUI Side with all the callbacks (Executed, PreviewExecutes, CanExecute, PreviewCanExecute)
You can also bind some input gestures (keyboard or) mouse corresponding to commands with InputBindings
There are some predefined commands like ApplicationCommands(Save, New,...) but it'up to you to define the behavior, what they do.
The interesting side of those CommandBindings is that they "tunnel" from the root of your hierarchy (Window) to the target and "bubble" to the root.
Crossing every level in the hierarchy (Grid, Stackpanel, ListBox...), the event can be handled (and stopped) at any level
Hope it helps, regards
Upvotes: 3