Separation of representations, presentation of commands (text, icon) and logic of commands (execute, CanExecute)

If TL; DR: see last paragraph.

Pure WPF "suggests" to place the view (controls, text, icons) in the views and the logic of commands (Execute, CanExecute methods) in the code. In addition to the fact that logic in both ( CommandBindings ) and code style is an unapproved practice, it does not help with XAML duplication at all: text, icons, large icons, tooltips and many other properties should be duplicated every time : the command is used: for the main menu, context menu, toolbar button, ribbon button, and other controls.

It seems that the first problem (truly separating views and logic) is solved with the help of DelegateCommand , RelayCommand and approaches this. Command logic moves to ViewModels (or controllers in the case of MVVMC), the code is clean, no CommandBindings and other meaningless representations.

However, I cannot find a generally accepted solution to the problem of duplication of presentation. I want to highlight team presentation (text, icons) and command logic ( Execute , CanExecute methods). All the code I could find places the view in code (by creating a RoutedCommand with additional properties such as Label and Icon ), or puts the code in the presentation (i.e. Handlers in the views and code). I do not like it either. I think the presentation should be completely in XAML, and the code should be completely in CS (either in the ViewModel or in the Controller).

Question: how to separate representations (XAML with controls that reference commands), command representations (shortcuts, icons, etc. for each command) and command logic (C # code for Execute , CanExecute , etc. in ViewModels or controllers)?

+7
source share
1 answer

There is no built-in solution to this problem, you will have to fold the sleeves and create the necessary structure yourself.

In a recent project that I was working on, I did just that. I created a concept called "action" that complements WPF ICommand other visual properties. It was something like this ...

 interface IAction { ICommand Command { get; } string DisplayText { get; } string ToolTipText{ get; } URI Icon { get; } } 

The application contained a collection of Action instances. Then they can be tied to menus, toolbars, etc ... allowing you to repeat the same instance of Action with different presentation styles. This is pretty simple MVVM stuff!

+4
source

All Articles