Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separating views, command presentation (Text, Icon) and command logic (Execute, CanExecute)

If TL;DR: see the last paragraph.

Pure WPF "suggests" putting presentation (controls, text, icons) into views and command logic (Execute, CanExecute methods) into code-behind. Besides putting logic both into views (CommandBindings) and code-behind being a frowned upon practice, it doesn't help at all with XAML duplication: text, icons, large icons, hints, and numerous other properties have to be duplicated every time a command is used: for main menu, for context menu, for toolbar button, for ribbon button and other controls.

Looks like the first problem (truly separating views and logic) is solved by DelegateCommand, RelayCommand and approaches like that. Command logic is moved into ViewModels (or Controllers in case of MVVMC), code-behind is clean, no CommandBindings and other nonsense in views.

However, I can't find a commonly accepted solution to the presentation duplication problem. I want to separate command presentation (text, icons) and command logic (Execute, CanExecute methods). All code I could find either puts presentation into code (by creating a RoutedCommand with additional properties like Label and Icon), or puts code into presentation (that is, handlers into views and code-behind). I don't like either. I think presentation should be completely in XAML, and code should be completely in CS (either in ViewModel or Controller).

Question: how to separate views (XAML with controls which reference commands), presentation of commands (labels, icons etc. for every command) and logic of commands (C# code for Execute, CanExecute etc. in ViewModels or Controllers)?

like image 576
Athari Avatar asked Nov 24 '12 18:11

Athari


1 Answers

There is no built-in solution to this problem, your're going to have to roll-up your sleeves and create the required structure yourself.

In a recent project I worked on, I did exactly this. I created a concept called an 'action' which supplements the WPF ICommand with 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. These could then be bound to menus, toolbars etc ... allowing the same Action instance to be re-used with various different presentation styles. It is all fairly straightforward MVVM stuff!

like image 95
ColinE Avatar answered Sep 30 '22 18:09

ColinE