Create a folder named Model and a class named Person. Define two properties, Name and Address. Initialize a List object of type person. Expose this object through the Persons property. Also expose an ICommand instance in this class. Create a view folder and a Person. Bind the command to the button control. Once the button is clicked, the command parameter is passed to the Execute method.
You can also bind a command to any control that supports the command property. The TextBox is bound with listView selectedItem. Override the OnStartup method of the Application class. Initialize a view and viewModel class and wrap a viewmodel to the view by the DataContext property. We cannot pass a parameter to the event but we can pass a parameter through a command. This is done by setting the CanExecute property of the event arguments to true.
The Executed handler simply shows a message box when the command is invoked. If you run the sample and press the button, you will see this message. A thing to notice is that this command has a default keyboard shortcut defined, which you get as an added bonus. In the first example, we implemented a CanExecute event that simply returned true, so that the button would be available all the time. However, this is of course not true for all buttons - in many cases, you want the button to be enabled or disabled depending on some sort of state in your application.
A very common example of this is the toggling of buttons for using the Windows Clipboard, where you want the Cut and Copy buttons to be enabled only when text is selected, and the Paste button to only be enabled when text is present in the clipboard.
This is exactly what we'll accomplish in this example:. So, we have this very simple interface with a couple of buttons and a TextBox control.
The first button will cut to the clipboard and the second one will paste from it. Each of these actions needs to perform what is typically the exact same piece of code, so in a WinForms application, you would have to define an event for each of them and then call a common function.
With the above example, that would lead to at least three event handlers and some code to handle the keyboard shortcut. Not an ideal situation. With WPF, Microsoft is trying to remedy that with a concept called commands. It allows you to define actions in one place and then refer to them from all your user interface controls like menu items, toolbar buttons and so on.
WPF will also listen for keyboard shortcuts and pass them along to the proper command, if any, making it the ideal way to offer keyboard shortcuts in an application. Commands also solve another hassle when dealing with multiple entrances to the same function.
In a WinForms application, you would be responsible for writing code that could disable user interface elements when the action was not available.
0コメント