title: MVVM Commands - How to move selected item form one listbox to another
body: <p>I found some great helper class for handle commands. It was found on some msdn blog.</p>
  
  <p>Here is it:</p>
  
  <pre class="lang-cs prettyprint-override"><code>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>
  
  <p>
  It is actually working very well when i need call void method. Here is a sample:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public class ViewModel1 : ViewModelBase
  {
      public ViewModel1()
      {
          DemoHeader dd = new DemoHeader(1, "Document-1");
          dd.Items.Add(new DemoItem(1, 1, "Article 1", "A-1", 9999, "szt", ObjectType.article));
          dd.Items.Add(new DemoItem(1, 2, "Article 2", "A-2", 5999, "szt", ObjectType.article));
  
          this.Add(dd);
      }
  
      #region ICommands
      private ICommand _Run = null;
      public ICommand Run
      {
          get
          {
              return _Run ?? (new DelegateCommand(RunMethod));
          }
      }
      #endregion
  
      #region CommandMethods
      public void RunMethod() //this method will be run
      {
  
      }
      #endregion
  }
  </code></pre>
  
  <p></p>
  
  <p>and you need to bind it in XAML code like this:</p>
  
  <pre><code>&lt;Button Command="{Binding Run}"/&gt;
  </code></pre>
  
  <p>Ok, i need to pass selected listboxitem from one listbox to another. I know how to do it using event driven pattern it would be like this:</p>
  
  <pre class="lang-cs prettyprint-override"><code>    private void Move(object sender, RoutedEventArgs e)
      {
          var fe = sender as FrameworkElement;
  
          if (fe.Name.Contains("da_")) //ALL DOWN
          {
             MoveSelectedItemToSourceListBox(lbArticles, lbWMSarticles);
          }
      }
  
      private void MoveSelectedItemToSourceListBox(ListBox source, ListBox desitination)
      {
          if (source.SelectedItem != null)
          {
              DemoItem item = source.SelectedItem as DemoItem;
              source.Items.Remove(item);
              item.AddItemToSourceList(dl); //here i'm using extension method to remove item from collection.
          }
      }
  </code></pre>
  
  <p></p>
  
  <p>But how to do it using MVVM and commands, what should i do? This is really tought to achive i guess. I rly want to learn properly way od coding. Could you help me and give me dome suggestions?</p>
  
  <p>Answer:</p>
  
  <p>Thanks guys for help. I did not know it would be so easy. :)</p>
  
  <p>Here is the answer:</p>
  
  <p>You need to add in your XAML code:</p>
  
  <pre><code>    &lt;ListBox Name="lbArticles" 
               ItemsSource="{Binding Source={StaticResource articles}}" 
               ItemTemplate="{StaticResource ListBoxItemTemplate}"
               SelectedItem="{Binding SelectedItem, Mode=TwoWay}"&gt;
      &lt;/ListBox&gt;
  </code></pre>
  
  <p>In your view class you need to add:</p>
  
  <pre class="lang-cs prettyprint-override"><code>          public class ViewModel2 : ViewModelBase
            {
                 DemoHeader dd = new DemoHeader(1, "Document-1");
                 dd.Items.Add(new DemoItem(1, 1, "Article 1", "A-1", 9999, "szt",ObjectType.article));
                 dd.Items.Add(new DemoItem(1, 2, "Article 2", "A-2", 5999, "szt", ObjectType.article));
  
                 this.Add(dd);
  
                 WMSarticleItems = new ObservableCollection&lt;DemoItem&gt;() //initialize object
            }
  
              public DemoItem SelectedItem { get; set; } //remember to make it public :)
  
  
              public ObservableCollection&lt;DemoItem&gt; WMSarticleItems //second listbox container remeber that it must be property with get; set; to propely binding
              {
                  get;
                  set;
              }
  
      //rest code
  </code></pre>
  
  <p></p>