내용 보기
작성자
관리자 (IP : 172.17.0.1)
날짜
2020-07-10 02:07
제목
[WPF] Handling events in an MVVM WPF application
Handling events in an MVVM WPF applicationPosted: June 30, 2013 Filed under: MVVM, WPF, XAML 6 Comments In a WPF application that uses the MVVM (Model-View-ViewModel) design pattern, the view model is the component that is responsible for handling the application’s presentation logic and state. This means that the view’s code-behind file should contain no code to handle events that are raised from any user interface (UI) element such as a Button or a ComboBox nor should it contain any domain specific logic. Ideally, the code-behind of a view ? typically a Window or a UserControl ? contains only a constructor that calls the InitializeComponent method and perhaps some additional code to control or interact with the view layer that is difficult or inefficient to express in XAML, e.g. complex animations. In other words, an MVVM application should not have any code like this where a button’s click event is handled in the code-behind of the view:
CommandsInstead, in addition to providing properties to expose data to be displayed or edited in the view, the view model defines actions that can be performed by the user and typically expose these as commands. A command is an object that implements theSystem.Windows.Input.ICommand interface and encapsulates the code for the action to be performed. It can be data bound to a UI control in the view to be invoked as a result of a mouse click, key press or any other input event. As well as the command being invoked as the user interacts with the UI, a UI control can be automatically enabled or disabled based on the command. The Execute method of the ICommand interface encapsulates the operation itself while the CanExecute method indicates whether the command can be invoked at a particular time or not. The interface also defines a CanExecuteChanged event that is raised on the UI thread to cause every invoking control to requery to check if the command can execute. WPF provides two implementations of the ICommand interface; the System.Windows.Input.RoutedCommand andSystem.Windows.Input.RoutedUICommand where the latter is a subclass of the former that simply adds a Text property that describes the command. However, neither of these implementations are especially suited to be used in a view model as they search the visual tree from the focused element and up for an element that has a matchingSystem.Windows.Input.CommandBinding object in its CommandBindings collection and then executes the Execute delegate for this particular CommandBinding. Since the command logic should reside in the view model, you don’t want to setup aCommandBinding in the view in order to connect the command to a visual element. Instead, you can create your own command by creating a class that implements the ICommand. The below implementation is a common one that invokes delegates for the Execute and CanExecute methods. If you are using Prism, the framework for building composite WPF and Silverlight applications from the Microsoft Patterns and Practices Team, there is a similar Microsoft.Practices.Prism.Commands.DelegateCommand class available.
The view model will then expose properties of this type for the view to bind to. Below is a sample implementation of a view model that exposes a ButtonClickCommand that will disable any UI control that is bound to it if the private string field _input, which is in turn exposed through a string property called Input, is empty. If you only pass a single delegate to the constructor of the DelegateCommand<T> class, it will assume that the command should always by available and the CanExecute method will always return true. Also note that when the value of the string property changes, a RaiseCanExecuteChanged method is called to raise the CanExecuteChanged event in order to update the status of any control in the view that is bound to the command.
With this approach you have now moved the presentation logic from the view to the view model. Instead of hooking up the button’s click handler, its Command property is now bound to the command defined in the view model and when the user clicks on the button the command’s Execute method will be invoked. EventTriggersThere is an alternative way of associating a control in the view with a command object exposed by the view model. Only some controls can actually bind to a command through the Command property, notably those derived fromSystem.Windows.Controls.Primitives.ButtonBase or System.Windows.Controls.MenuItem. If you want to attach a command to some other control or when you want to invoke a command on an event other than the click event for a button, you can use Expression Blend interaction triggers and the System.Windows.Interactivity.InvokeCommandAction class. Below is an example on how you would execute a command object called MouseEnterCommand in the view model when the user moves the mouse pointer over a Rectangle element in the view. You specify the event for which the command will be executed in the EventName property of the EventTrigger. Remember to add a reference to System.Windows.Interactivity.dll for this to compile.
CommandParametersIf you wish to pass a parameter to a command from the view you do so by using the CommandParameter property. The type argument of the generic DelegateCommand<T> class specifies the type of the command parameter that gets passed to the Execute and CanExecute methods. The CommandParameter property exists in both the ButtonBase and MenuItem derived controls as well as in the InvokeCommandAction class:
CallMethodActionBesides the InvokeCommandAction class, there is also another class named CallMethodAction that can be used to invoke a method in the view model from the view without using commands. It has a MethodName property for specifying the name of the method to call and a TargetObject property that needs to be bound to an instance of the class containing the method, i.e. the view model:
Note that the CallMethodAction class is defined in another assembly and namespace and you will need to add a reference to Microsoft.Expressions.Interactions.dll to be able to use it. Also note that it doesn’t support parameters. |
출처1
http://blog.magnusmontin.net/2013/06/30/handling-events-in-an-mvvm-wpf-application/
출처2