Click here to Skip to main content
14,484,433 members

Sinking RoutedCommands to ViewModel Commands in WPF

Rate this:
5.00 (3 votes)
Please Sign up or sign in to vote.
5.00 (3 votes)
17 Dec 2012CPOL
This is an alternative for "Using RoutedCommands with a ViewModel in WPF".


I found myself searching for a solution to using the RoutedCommand and sinking it to a ViewModel's command. I found Josh Smith's solution, but I found it hard to read when the Xaml was done. I wanted something that read nicer.

Why don't I just always used view model commands? Well, sometimes I cannot get around it. When my products use Third Party Controls, they typically implement the standard RoutedUICommands, like those in the System.Windows.Input namespace, such as ApplicationsCommands, MediaCommands, and NavigationCommands. I want to use my controls that I bought, but I also want to stick with my MVVM design. 


My solution entails adding an invisible UserControl called CommandSinkControl. That control associates RoutedCommands with view model ICommands. Then in your normal CommandBindings, you forward the event call to the CommandSinkControl's public methods DoExecuted and DoCanExecute to handle the event. 

The Code  

There is just one control that you have to add to your code base, CommandSinkControl.  


<UserControl x:Class="CommandSink.CommandSinkControl"





using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Markup;

namespace CommandSink {
    public partial class CommandSinkControl : UserControl {
        private static readonly DependencyPropertyKey SinksPropertyKey =

        public static readonly DependencyProperty SinksProperty =

        public CommandSinkBindingCollection CommandSinkBindings {
            get { return (CommandSinkBindingCollection)this.GetValue(SinksProperty); }
            private set { this.SetValue(SinksPropertyKey, value); }

        public CommandSinkControl() {
            this.CommandSinkBindings = new CommandSinkBindingCollection();
            this.CommandSinkBindings.CollectionChanged += this.Sinks_OnCollectionChanged;

        protected override IEnumerator LogicalChildren {
            get {
                if (this.CommandSinkBindings == null) {
                    yield break;
                foreach (var sink in this.CommandSinkBindings) {
                    yield return sink;

        private void Sinks_OnCollectionChanged(object sender,
                                               NotifyCollectionChangedEventArgs e) {
            switch (e.Action) {
                case NotifyCollectionChangedAction.Add:
                    foreach (var sink in e.NewItems) {

        public void DoCanExecute(object sender, CanExecuteRoutedEventArgs e) {
            var commandSinkBinding = this.CommandSinkBindings
                                         .FirstOrDefault(csb => csb.Faucet == e.Command);
            if (commandSinkBinding != null && commandSinkBinding.Drain != null) {
                e.Handled = true;
                e.CanExecute = commandSinkBinding.Drain.CanExecute(e.Parameter);

        public void DoExecuted(object sender, ExecutedRoutedEventArgs e) {
            var commandSinkBinding = this.CommandSinkBindings
                                         .FirstOrDefault(csb => csb.Faucet == e.Command);
            if (commandSinkBinding != null && commandSinkBinding.Drain != null) {
                e.Handled = true;

    public sealed class CommandSinkBindingCollection
        : ObservableCollection<CommandSinkBinding> {

    public class CommandSinkBinding : FrameworkElement {
        public static readonly DependencyProperty FaucetProperty =

        public RoutedCommand Faucet {
            get { return (RoutedCommand) this.GetValue(FaucetProperty); }
            set { this.SetValue(FaucetProperty, value); }

        public static readonly DependencyProperty DrainProperty =

        public ICommand Drain {
            get { return (ICommand) this.GetValue(DrainProperty); }
            set { this.SetValue(DrainProperty, value); }


In the following example, I have hooked up the CommandSinkControl such that it sinks the ApplicationCommands.Open RoutedCommand to the OpenCommand that I've defined in my View Model. 


<Window x:Class="CommandSink.MainWindow"




        Title="CommandSink" SizeToContent="WidthAndHeight" ResizeMode="NoResize">
    <!-- Normal Command Bindings to RoutedCommands -->
        <CommandBinding Command="ApplicationCommands.Open"



        <!-- Example KeyBinding with Command Binding to a Routed Command -->
        <KeyBinding Gesture="CTRL+O" Command="ApplicationCommands.Open"/>

        <!-- Make sure this is at the top so that CanExecute events can use CommandSinkControl.
             It defaults to hidden, so you don't have to hide it.-->
        <local:CommandSinkControl x:Name="CommandSinkControl">
            <!-- Sinks the ApplicationCommands.Open RoutedUICommand to the OpenCommand -->
            <local:CommandSinkBinding Faucet="ApplicationCommands.Open"

                                      Drain="{Binding OpenCommand}"/>

        <CheckBox Margin="10"

                  Content="Toggles the Open button's enabled state"

                  IsChecked="{Binding OpenCanExecute}"/>

        <!-- Example Button with Command Binding to a Routed Command-->
        <Button Margin="10" Content="Open" HorizontalAlignment="Left"



using System.Windows;
using System.Windows.Input;

namespace CommandSink {
    /// <summary>
    ///   Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window {
        public MainWindow() {
            this.DataContext = new MainViewModel();

        private void CommandBinding_OnExecuted(object sender, ExecutedRoutedEventArgs e) {
            this.CommandSinkControl.DoExecuted(sender, e);

        private void CommandBinding_OnCanExecute(object sender, CanExecuteRoutedEventArgs e) {
            this.CommandSinkControl.DoCanExecute(sender, e);


using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
using Microsoft.Practices.Prism.Commands;

namespace CommandSink {
    public class MainViewModel : INotifyPropertyChanged {
        public ICommand OpenCommand { get; private set; }

        private bool m_openCanExecute;
        public bool OpenCanExecute {
            get { return this.m_openCanExecute; }
            set {
                if (value != this.m_openCanExecute) {
                    this.m_openCanExecute = value;

        public MainViewModel() {
            this.OpenCommand = new DelegateCommand(this.OpenCommand_OnExecuted,

        private bool OpenCommand_OnCanExecute() {
            return this.OpenCanExecute;

        private void OpenCommand_OnExecuted() {
            MessageBox.Show("Open Command");

        #region Implementation of INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName) {
            var handler = this.PropertyChanged;
            if (handler != null) {
                handler(this, new PropertyChangedEventArgs(propertyName));

Points of Interest 

While you have to add a little wire-up code to the code-behind of the view, I found this acceptable to gain the added readability. 

You might also ask why I created an invisible UserControl instead of just putting it in the Window.Resources. It was crucial that Drain="{Binding OpenCommand}" worked. To do that, I needed it to be part of the LogicalTree and inherit the DataContext such that I could use DataBinding. Do you have a better solution to do this? Please let me know! 

Thank You!

Thank you for reading my article. I hope I was clear and understandable. Please provide comments, suggestions, and/or concerns! I'd love to hear them! Thank you! 


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Charles Mathis
Software Developer (Senior)
United States United States
Charles creates software for Windows and the Web. He works as a Senior Software Engineer at a leading Financial Services company.

Comments and Discussions

Questionthanks Pin
taleofsixstrings17-Sep-13 21:06
Membertaleofsixstrings17-Sep-13 21:06 
SuggestionCould also use System.Windows.Interactivity to create a behavior that maps the RoutedCommand to a ICommand Pin
Member 402078415-Feb-13 13:23
MemberMember 402078415-Feb-13 13:23 
GeneralRe: Could also use System.Windows.Interactivity to create a behavior that maps the RoutedCommand to a ICommand Pin
Charles Mathis30-Dec-13 3:11
MemberCharles Mathis30-Dec-13 3:11 
QuestionNice idea Pin
Sacha Barber18-Dec-12 3:25
MemberSacha Barber18-Dec-12 3:25 
AnswerRe: Nice idea Pin
Charles Mathis18-Dec-12 4:06
MemberCharles Mathis18-Dec-12 4:06 
GeneralRe: Nice idea Pin
William E. Kempf18-Dec-12 9:32
MemberWilliam E. Kempf18-Dec-12 9:32 
AnswerRe: Nice idea Pin
Charles Mathis18-Dec-12 13:13
MemberCharles Mathis18-Dec-12 13:13 
GeneralRe: Nice idea Pin
William E. Kempf19-Dec-12 2:48
MemberWilliam E. Kempf19-Dec-12 2:48 
Charles Mathis wrote:
Two framework authors commenting on my post. Quite an honor! It's either I've
done something right, or something horribly wrong!

What you've done is invented and interesting, even if there's things about it I don't like. So you're definitely not doing anything "horribly wrong", though that's not why I chimed in on this thread. You're reply to Sacha just misrepresented the view services concept that I felt needed some correcting.

Charles Mathis wrote:
1) In order to use a View specific service, I would have to register my Views
with a Behavior, thereby putting a requirement on my Views in order to give my
ViewModel access to a View specific service like ICommandTarget in Onyx.

Be careful when jumping to conclusions that you don't make such all or nothing claims. With larger projects probably the best approach is to use some framework (even one built by yourself) that can create your ViewModels, wiring them up with the services they need. That framework does not need to use a behavior, however. Nor is it necessary to use a framework at all. The code Sacha showed you didn't use any framework, and is a very legitimate way to implement this pattern, especially for smaller/simpler applications.

Charles Mathis wrote:
2) The CommandSinkControl provides a "Xaml only" solution (minus the little bit
of code-behind) to associate RoutedCommands to ViewModel commands. I prefer to
do that in the View, too, as it is closer to the Third Party Controls that
require it, but this requirement is rather insignificant.

You've said this more than once, and it's obviously why you prefer your approach. In this, we'll have to agree to disagree, I think. First, I still feel like your clouding the conversation when you continually talk about both "RoutedCommands" and "ViewModel commands". I realize your solution links a RoutedCommand to an ICommand exposed by your ViewModel, but in my eyes that's an implementation detail you shouldn't care about. In the service approach there is no special ICommand exposed by the ViewModel. The RoutedCommand is the only command used in either the View or the ViewModel. This means the comment "I prefer to do that in the View, too, as it is closer to the Third Party Controls" is meaningless when we're talking about the service solution. What's being done in the code rather than in XAML is associating the RoutedCommand with handler methods on the ViewModel, which is the exact same thing you do with your ICommand exposed by your ViewModels. The service approach has the same amount of (basically identical) code in the ViewModel, and less XAML code in the View, with direct usage of the RoutedCommand instead of an indirect association to an intermediary. While your approach is interesting, I don't see how you can make the claims you've made here, with regard to doing any associations in the View.

All that said, I'm not trying to convince you that you've done something wrong. I don't believe that to be the case at all. It's not how I'd do things, obviously, and there's reasons why, but that doesn't mean what you've done is wrong or not even a useful idea that I might employ in other situations. Not sure I ever will, because what you've done is a heavier weight version of an attached property/behavior, but there are some subtle differences that may be worth considering for something in the future. It is an interesting approach, as I said.
William E. Kempf

GeneralRe: Nice idea Pin
Sacha Barber20-Dec-12 1:57
MemberSacha Barber20-Dec-12 1:57 
GeneralRe: Nice idea Pin
Charles Mathis20-Dec-12 9:37
MemberCharles Mathis20-Dec-12 9:37 
GeneralRe: Nice idea Pin
Sacha Barber21-Dec-12 22:54
MemberSacha Barber21-Dec-12 22:54 
GeneralRe: Nice idea Pin
Sacha Barber20-Dec-12 1:54
MemberSacha Barber20-Dec-12 1:54 
QuestionArticle should be "Syncing" Pin
FatCatProgrammer18-Dec-12 0:35
MemberFatCatProgrammer18-Dec-12 0:35 
AnswerRe: Article should be "Syncing" Pin
Charles Mathis18-Dec-12 4:15
MemberCharles Mathis18-Dec-12 4:15 
Generalcool! Pin
poi11917-Dec-12 23:54
Memberpoi11917-Dec-12 23:54 
GeneralRe: cool! Pin
Charles Mathis18-Dec-12 4:16
MemberCharles Mathis18-Dec-12 4:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Posted 17 Dec 2012


13 bookmarked