title: Updating a reference to a command of a nested ViewModel?
body: <p>I know I'm probably missing something simple and obvious, but at the moment it eludes me.</p>
  
  <p>I'm attempting to use the MVVM pattern.</p>
  
  <p>How do you update a reference to a command in a viewmodel that is linked to a child viewmodel?</p>
  
  <p>I've got a view (MainView) bound to a viewmodel (MainViewModel).
  On MainView, I've got an instance of another view (SummaryView) bound to a viewmodel (SummaryViewModel). SummaryViewModel contains a collection of a third viewmodel (SummaryFilterViewModel).</p>
  
  <p>On SummaryView, there is a TabControl and each tab on it is bound to one of the SummaryFilterViewModel instances in the SummaryViewodel collection.</p>
  
  <p>On MainView there is a button that is bound to a command in MainViewModel.</p>
  
  <p>What I want to happen is for the command logic to live within the SummaryFilterViewModel class. So, whichever tab is currently displayed needs to be wired up to the command that the button on MainView fires.</p>
  
  <p>What I tried to do was this:</p>
  
  <ol>
  <li>The individual SummaryFilterViewModel objects stored in the collection in SummaryViewModel hold the actual implementations of the ShoutCommand.</li>
  <li>A CommandReference object in the XAML of MainView binds to a ShoutCommand property of the MainViewModel</li>
  <li>The ShoutCommand property of the MainViewModel returns a reference to the ShoutCommand property of the SummaryViewModel object stored in MainViewModel.</li>
  <li>The ShoutCommand property of the SummaryViewModel returns a reference to the ShoutCommand property of whichever is the currently selected SummaryFilterViewModel.</li>
  </ol>
  
  <p>What happens, is that the command does not get updated when the user changes tabs.</p>
  
  <p>Am I way off base in how to implement this?
  Do I need to move the implementation of the command into the SummaryViewModel class?</p>
  
  <p>Thanks in advance for any help!</p>
  
  <p>The source to my solution is listed below:</p>
  
  <h2>ViewModels</h2>
  
  <p><em><strong>SummaryView.xaml</em></strong></p>
  
  <pre><code>&lt;UserControl x:Class="NestedCommands.Views.SummaryView"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
           xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
           xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
           mc:Ignorable="d" 
           d:DesignHeight="309" d:DesignWidth="476"&gt;
  &lt;Grid&gt;
      &lt;TabControl SelectedIndex="{Binding SelectedTabIndex}"&gt;
          &lt;TabItem DataContext="{Binding Filters[0]}" Header="{Binding FilterName}"&gt;
              &lt;ListBox ItemsSource="{Binding ListData}" /&gt;
          &lt;/TabItem&gt;
          &lt;TabItem DataContext="{Binding Filters[1]}" Header="{Binding FilterName}"&gt;
              &lt;ListBox ItemsSource="{Binding ListData}" /&gt;
          &lt;/TabItem&gt;
          &lt;TabItem DataContext="{Binding Filters[2]}" Header="{Binding FilterName}"&gt;
              &lt;ListBox ItemsSource="{Binding ListData}" /&gt;
          &lt;/TabItem&gt;
      &lt;/TabControl&gt;
  &lt;/Grid&gt;
  </code></pre>
  
  <p></p>
  
  <p><em><strong>MainView.xaml</em></strong></p>
  
  <pre><code>&lt;Window x:Class="NestedCommands.Views.MainView"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:v="clr-namespace:NestedCommands.Views"
      xmlns:c="clr-namespace:NestedCommands.Commands"
      Title="MainView" Height="336" Width="420"&gt;
  &lt;Window.Resources&gt;
      &lt;c:CommandReference x:Key="ShoutCommandReference" Command="{Binding ShoutCommand}" /&gt;
  &lt;/Window.Resources&gt;
  &lt;Grid&gt;
      &lt;Grid.RowDefinitions&gt;
          &lt;RowDefinition Height="1*" /&gt;
          &lt;RowDefinition Height="Auto" /&gt;
      &lt;/Grid.RowDefinitions&gt;
      &lt;v:SummaryView Grid.Row="0"
                     DataContext="{Binding SummaryViewModel}" /&gt;
      &lt;Button Content="Shout Command"
              Grid.Row="1"
              Command="{StaticResource ShoutCommandReference}" /&gt;
  &lt;/Grid&gt;
  </code></pre>
  
  <p></p>
  
  <hr>
  
  <h2>Command Classes</h2>
  
  <p><em><strong>CommandReference.cs</em></strong></p>
  
  <pre><code>using System;
  using System.Windows;
  using System.Windows.Input;
  
  namespace NestedCommands.Commands
  {
      /// &lt;summary&gt;
      /// This class facilitates associating a key binding in XAML markup to a command
      /// defined in a View Model by exposing a Command dependency property.
      /// The class derives from Freezable to work around a limitation in WPF when data-binding from XAML.
      /// &lt;/summary&gt;
      public class CommandReference : Freezable, ICommand
      {
          public CommandReference()
          {
              // Blank
          }
  
          public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(CommandReference), new PropertyMetadata(new PropertyChangedCallback(OnCommandChanged)));
  
          public ICommand Command
          {
              get { return (ICommand)GetValue(CommandProperty); }
              set { SetValue(CommandProperty, value); }
          }
  
          #region ICommand Members
  
          public bool CanExecute(object parameter)
          {
              if (Command != null)
                  return Command.CanExecute(parameter);
              return false;
          }
  
          public void Execute(object parameter)
          {
              Command.Execute(parameter);
          }
  
          public event EventHandler CanExecuteChanged;
  
          private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
          {
              CommandReference commandReference = d as CommandReference;
              ICommand oldCommand = e.OldValue as ICommand;
              ICommand newCommand = e.NewValue as ICommand;
  
              if (oldCommand != null)
              {
                  oldCommand.CanExecuteChanged -= commandReference.CanExecuteChanged;
              }
              if (newCommand != null)
              {
                  newCommand.CanExecuteChanged += commandReference.CanExecuteChanged;
              }
          }
  
          #endregion
  
          #region Freezable
  
          protected override Freezable CreateInstanceCore()
          {
              throw new NotImplementedException();
          }
  
          #endregion
      }
  }
  </code></pre>
  
  <p><em><strong>DelegateCommand.cs</em></strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Windows;
  using System.Windows.Input;
  
  namespace NestedCommands.Commands
  {
      /// &lt;summary&gt;
      ///     This class allows delegating the commanding logic to methods passed as parameters,
      ///     and enables a View to bind commands to objects that are not part of the element tree.
      /// &lt;/summary&gt;
      public class DelegateCommand : ICommand
      {
          #region Constructors
  
          /// &lt;summary&gt;
          ///     Constructor
          /// &lt;/summary&gt;
          public DelegateCommand(Action executeMethod)
              : this(executeMethod, null, false)
          {
          }
  
          /// &lt;summary&gt;
          ///     Constructor
          /// &lt;/summary&gt;
          public DelegateCommand(Action executeMethod, Func&lt;bool&gt; canExecuteMethod)
              : this(executeMethod, canExecuteMethod, false)
          {
          }
  
          /// &lt;summary&gt;
          ///     Constructor
          /// &lt;/summary&gt;
          public DelegateCommand(Action executeMethod, Func&lt;bool&gt; canExecuteMethod, bool isAutomaticRequeryDisabled)
          {
              if (executeMethod == null)
              {
                  throw new ArgumentNullException("executeMethod");
              }
  
              _executeMethod = executeMethod;
              _canExecuteMethod = canExecuteMethod;
              _isAutomaticRequeryDisabled = isAutomaticRequeryDisabled;
          }
  
          #endregion
  
          #region Public Methods
  
          /// &lt;summary&gt;
          ///     Method to determine if the command can be executed
          /// &lt;/summary&gt;
          public bool CanExecute()
          {
              if (_canExecuteMethod != null)
              {
                  return _canExecuteMethod();
              }
              return true;
          }
  
          /// &lt;summary&gt;
          ///     Execution of the command
          /// &lt;/summary&gt;
          public void Execute()
          {
              if (_executeMethod != null)
              {
                  _executeMethod();
              }
          }
  
          /// &lt;summary&gt;
          ///     Property to enable or disable CommandManager's automatic requery on this command
          /// &lt;/summary&gt;
          public bool IsAutomaticRequeryDisabled
          {
              get
              {
                  return _isAutomaticRequeryDisabled;
              }
              set
              {
                  if (_isAutomaticRequeryDisabled != value)
                  {
                      if (value)
                      {
                          CommandManagerHelper.RemoveHandlersFromRequerySuggested(_canExecuteChangedHandlers);
                      }
                      else
                      {
                          CommandManagerHelper.AddHandlersToRequerySuggested(_canExecuteChangedHandlers);
                      }
                      _isAutomaticRequeryDisabled = value;
                  }
              }
          }
  
          /// &lt;summary&gt;
          ///     Raises the CanExecuteChaged event
          /// &lt;/summary&gt;
          public void RaiseCanExecuteChanged()
          {
              OnCanExecuteChanged();
          }
  
          /// &lt;summary&gt;
          ///     Protected virtual method to raise CanExecuteChanged event
          /// &lt;/summary&gt;
          protected virtual void OnCanExecuteChanged()
          {
              CommandManagerHelper.CallWeakReferenceHandlers(_canExecuteChangedHandlers);
          }
  
          #endregion
  
          #region ICommand Members
  
          /// &lt;summary&gt;
          ///     ICommand.CanExecuteChanged implementation
          /// &lt;/summary&gt;
          public event EventHandler CanExecuteChanged
          {
              add
              {
                  if (!_isAutomaticRequeryDisabled)
                  {
                      CommandManager.RequerySuggested += value;
                  }
                  CommandManagerHelper.AddWeakReferenceHandler(ref _canExecuteChangedHandlers, value, 2);
              }
              remove
              {
                  if (!_isAutomaticRequeryDisabled)
                  {
                      CommandManager.RequerySuggested -= value;
                  }
                  CommandManagerHelper.RemoveWeakReferenceHandler(_canExecuteChangedHandlers, value);
              }
          }
  
          bool ICommand.CanExecute(object parameter)
          {
              return CanExecute();
          }
  
          void ICommand.Execute(object parameter)
          {
              Execute();
          }
  
          #endregion
  
          #region Data
  
          private readonly Action _executeMethod = null;
          private readonly Func&lt;bool&gt; _canExecuteMethod = null;
          private bool _isAutomaticRequeryDisabled = false;
          private List&lt;WeakReference&gt; _canExecuteChangedHandlers;
  
          #endregion
      }
  
      /// &lt;summary&gt;
      ///     This class allows delegating the commanding logic to methods passed as parameters,
      ///     and enables a View to bind commands to objects that are not part of the element tree.
      /// &lt;/summary&gt;
      /// &lt;typeparam name="T"&gt;Type of the parameter passed to the delegates&lt;/typeparam&gt;
      public class DelegateCommand&lt;T&gt; : ICommand
      {
          #region Constructors
  
          /// &lt;summary&gt;
          ///     Constructor
          /// &lt;/summary&gt;
          public DelegateCommand(Action&lt;T&gt; executeMethod)
              : this(executeMethod, null, false)
          {
          }
  
          /// &lt;summary&gt;
          ///     Constructor
          /// &lt;/summary&gt;
          public DelegateCommand(Action&lt;T&gt; executeMethod, Func&lt;T, bool&gt; canExecuteMethod)
              : this(executeMethod, canExecuteMethod, false)
          {
          }
  
          /// &lt;summary&gt;
          ///     Constructor
          /// &lt;/summary&gt;
          public DelegateCommand(Action&lt;T&gt; executeMethod, Func&lt;T, bool&gt; canExecuteMethod, bool isAutomaticRequeryDisabled)
          {
              if (executeMethod == null)
              {
                  throw new ArgumentNullException("executeMethod");
              }
  
              _executeMethod = executeMethod;
              _canExecuteMethod = canExecuteMethod;
              _isAutomaticRequeryDisabled = isAutomaticRequeryDisabled;
          }
  
          #endregion
  
          #region Public Methods
  
          /// &lt;summary&gt;
          ///     Method to determine if the command can be executed
          /// &lt;/summary&gt;
          public bool CanExecute(T parameter)
          {
              if (_canExecuteMethod != null)
              {
                  return _canExecuteMethod(parameter);
              }
              return true;
          }
  
          /// &lt;summary&gt;
          ///     Execution of the command
          /// &lt;/summary&gt;
          public void Execute(T parameter)
          {
              if (_executeMethod != null)
              {
                  _executeMethod(parameter);
              }
          }
  
          /// &lt;summary&gt;
          ///     Raises the CanExecuteChaged event
          /// &lt;/summary&gt;
          public void RaiseCanExecuteChanged()
          {
              OnCanExecuteChanged();
          }
  
          /// &lt;summary&gt;
          ///     Protected virtual method to raise CanExecuteChanged event
          /// &lt;/summary&gt;
          protected virtual void OnCanExecuteChanged()
          {
              CommandManagerHelper.CallWeakReferenceHandlers(_canExecuteChangedHandlers);
          }
  
          /// &lt;summary&gt;
          ///     Property to enable or disable CommandManager's automatic requery on this command
          /// &lt;/summary&gt;
          public bool IsAutomaticRequeryDisabled
          {
              get
              {
                  return _isAutomaticRequeryDisabled;
              }
              set
              {
                  if (_isAutomaticRequeryDisabled != value)
                  {
                      if (value)
                      {
                          CommandManagerHelper.RemoveHandlersFromRequerySuggested(_canExecuteChangedHandlers);
                      }
                      else
                      {
                          CommandManagerHelper.AddHandlersToRequerySuggested(_canExecuteChangedHandlers);
                      }
                      _isAutomaticRequeryDisabled = value;
                  }
              }
          }
  
          #endregion
  
          #region ICommand Members
  
          /// &lt;summary&gt;
          ///     ICommand.CanExecuteChanged implementation
          /// &lt;/summary&gt;
          public event EventHandler CanExecuteChanged
          {
              add
              {
                  if (!_isAutomaticRequeryDisabled)
                  {
                      CommandManager.RequerySuggested += value;
                  }
                  CommandManagerHelper.AddWeakReferenceHandler(ref _canExecuteChangedHandlers, value, 2);
              }
              remove
              {
                  if (!_isAutomaticRequeryDisabled)
                  {
                      CommandManager.RequerySuggested -= value;
                  }
                  CommandManagerHelper.RemoveWeakReferenceHandler(_canExecuteChangedHandlers, value);
              }
          }
  
          bool ICommand.CanExecute(object parameter)
          {
              // if T is of value type and the parameter is not
              // set yet, then return false if CanExecute delegate
              // exists, else return true
              if (parameter == null &amp;&amp;
                  typeof(T).IsValueType)
              {
                  return (_canExecuteMethod == null);
              }
              return CanExecute((T)parameter);
          }
  
          void ICommand.Execute(object parameter)
          {
              Execute((T)parameter);
          }
  
          #endregion
  
          #region Data
  
          private readonly Action&lt;T&gt; _executeMethod = null;
          private readonly Func&lt;T, bool&gt; _canExecuteMethod = null;
          private bool _isAutomaticRequeryDisabled = false;
          private List&lt;WeakReference&gt; _canExecuteChangedHandlers;
  
          #endregion
      }
  
      /// &lt;summary&gt;
      ///     This class contains methods for the CommandManager that help avoid memory leaks by
      ///     using weak references.
      /// &lt;/summary&gt;
      internal class CommandManagerHelper
      {
          internal static void CallWeakReferenceHandlers(List&lt;WeakReference&gt; handlers)
          {
              if (handlers != null)
              {
                  // Take a snapshot of the handlers before we call out to them since the handlers
                  // could cause the array to me modified while we are reading it.
  
                  EventHandler[] callees = new EventHandler[handlers.Count];
                  int count = 0;
  
                  for (int i = handlers.Count - 1; i &gt;= 0; i--)
                  {
                      WeakReference reference = handlers[i];
                      EventHandler handler = reference.Target as EventHandler;
                      if (handler == null)
                      {
                          // Clean up old handlers that have been collected
                          handlers.RemoveAt(i);
                      }
                      else
                      {
                          callees[count] = handler;
                          count++;
                      }
                  }
  
                  // Call the handlers that we snapshotted
                  for (int i = 0; i &lt; count; i++)
                  {
                      EventHandler handler = callees[i];
                      handler(null, EventArgs.Empty);
                  }
              }
          }
  
          internal static void AddHandlersToRequerySuggested(List&lt;WeakReference&gt; handlers)
          {
              if (handlers != null)
              {
                  foreach (WeakReference handlerRef in handlers)
                  {
                      EventHandler handler = handlerRef.Target as EventHandler;
                      if (handler != null)
                      {
                          CommandManager.RequerySuggested += handler;
                      }
                  }
              }
          }
  
          internal static void RemoveHandlersFromRequerySuggested(List&lt;WeakReference&gt; handlers)
          {
              if (handlers != null)
              {
                  foreach (WeakReference handlerRef in handlers)
                  {
                      EventHandler handler = handlerRef.Target as EventHandler;
                      if (handler != null)
                      {
                          CommandManager.RequerySuggested -= handler;
                      }
                  }
              }
          }
  
          internal static void AddWeakReferenceHandler(ref List&lt;WeakReference&gt; handlers, EventHandler handler)
          {
              AddWeakReferenceHandler(ref handlers, handler, -1);
          }
  
          internal static void AddWeakReferenceHandler(ref List&lt;WeakReference&gt; handlers, EventHandler handler, int defaultListSize)
          {
              if (handlers == null)
              {
                  handlers = (defaultListSize &gt; 0 ? new List&lt;WeakReference&gt;(defaultListSize) : new List&lt;WeakReference&gt;());
              }
  
              handlers.Add(new WeakReference(handler));
          }
  
          internal static void RemoveWeakReferenceHandler(List&lt;WeakReference&gt; handlers, EventHandler handler)
          {
              if (handlers != null)
              {
                  for (int i = handlers.Count - 1; i &gt;= 0; i--)
                  {
                      WeakReference reference = handlers[i];
                      EventHandler existingHandler = reference.Target as EventHandler;
                      if ((existingHandler == null) || (existingHandler == handler))
                      {
                          // Clean up old handlers that have been collected
                          // in addition to the handler that is to be removed.
                          handlers.RemoveAt(i);
                      }
                  }
              }
          }
      }
  }
  </code></pre>
  
  <hr>
  
  <h2>View Models</h2>
  
  <p><em><strong>ViewModelBase.cs</em></strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.ComponentModel;
  
  namespace NestedCommands.ViewModels
  {
      class ViewModelBase : INotifyPropertyChanged
      {
          public event PropertyChangedEventHandler PropertyChanged;
  
          protected void OnPropertyChanged(object sender, string propertyName)
          {
              if (this.PropertyChanged != null)
              {
                  PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
              }
          }
      }
  }
  </code></pre>
  
  <p><em><strong>MainViewModel.cs</em></strong></p>
  
  <pre><code>using System;
  using System.Windows.Input;
  
  namespace NestedCommands.ViewModels
  {
      class MainViewModel : ViewModelBase
      {
          public MainViewModel()
          {
              _SummaryViewModel = new SummaryViewModel();
          }
  
          private SummaryViewModel _SummaryViewModel;
          public SummaryViewModel SummaryViewModel
          {
              get { return _SummaryViewModel; }
              set
              {
                  _SummaryViewModel = value;
                  OnPropertyChanged(this, "SummaryViewModel");
              }
          }
  
          public ICommand ShoutCommand
          {
              get { return _SummaryViewModel.ShoutCommand; }
          }
      }
  }
  </code></pre>
  
  <p><em><strong>SummaryViewModel.cs</em></strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using NestedCommands.Commands;
  using System.Windows.Input;
  
  namespace NestedCommands.ViewModels
  {
      class SummaryViewModel : ViewModelBase
      {
          #region Constructor
  
          public SummaryViewModel()
          {
              List&lt;SummaryFilterViewModel&gt; filters = new List&lt;SummaryFilterViewModel&gt;();
              filters.Add(new SummaryFilterViewModel("Filter 1"));
              filters.Add(new SummaryFilterViewModel("Filter 2"));
              filters.Add(new SummaryFilterViewModel("Filter 3"));
              Filters = filters;
          }
  
          #endregion
  
          #region Properties
  
          private List&lt;SummaryFilterViewModel&gt; _Filters;
          public List&lt;SummaryFilterViewModel&gt; Filters
          {
              get { return _Filters; }
              set
              {
                  _Filters = value;
                  OnPropertyChanged(this, "Filters");
              }
          }
  
          private int _SelectedTabIndex;
          public int SelectedTabIndex
          {
              get { return _SelectedTabIndex; }
              set
              {
                  _SelectedTabIndex = value;
                  OnPropertyChanged(this, "SelectedTabIndex");
              }
          }
  
          #endregion
  
          #region Command References
  
          public ICommand ShoutCommand
          {
              get { return Filters[SelectedTabIndex].ShoutCommand; }
          }
  
          #endregion
      }
  }
  </code></pre>
  
  <p><em><strong>SummaryFilterViewModel.cs</em></strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using NestedCommands.Commands;
  using System.Windows.Input;
  
  namespace NestedCommands.ViewModels
  {
      class SummaryFilterViewModel : ViewModelBase
      {
          #region Constructor
  
          public SummaryFilterViewModel(string FilterName)
          {
              this.FilterName = FilterName;
  
              List&lt;string&gt; listData = new List&lt;string&gt;();
              for (int i = 1; i &lt; 10; i++)
              {
                  listData.Add(string.Format("{0}: {1}", FilterName, i));
              }
              ListData = listData;
          }
  
          #endregion
  
          #region Properties
  
          private string _FilterName;
          public string FilterName
          {
              get { return _FilterName; }
              set
              {
                  _FilterName = value;
                  OnPropertyChanged(this, "FilterName");
              }
          }
  
          private List&lt;string&gt; _ListData;
          public List&lt;string&gt; ListData
          {
              get { return _ListData; }
              set
              {
                  _ListData = value;
                  OnPropertyChanged(this, "ListData");
              }
          }
  
          #endregion
  
          #region Shout Command
  
          private DelegateCommand _ShoutCommand;
          public ICommand ShoutCommand
          {
              get { return _ShoutCommand ?? (_ShoutCommand = new DelegateCommand(Shout, CanShout)); }
          }
  
          private void Shout()
          {
              System.Windows.MessageBox.Show(string.Format("Called from SummaryFilterViewModel: {0}", FilterName));
          }
  
          private bool CanShout()
          {
              return true;
          }
  
          #endregion
      }
  }
  </code></pre>