title: Binding commands to dynamically created buttons
body: <p>I'm trying to create a program which would allow me to choose a program to start a different program based on different requirements. Basically I have a JSON document specifying Name, Path, Icon etc and a button is created for each entry.</p>
  
  <p>I have a <code>ButtonDef</code> class that looks like this:</p>
  
  <pre><code>public class ButtonDef
  {
      public int Id { get; set; }
      public string Caption { get; set; }
      public string Cmd { get; set; }
      public string Icon { get; set; }
  }
  </code></pre>
  
  <p>I create an <code>ObservableCollection&lt;ButtonDef&gt;</code> called <code>Buttons</code> which is a public property in my <code>ViewModel</code> and populate is with <code>ButtonDef</code>s.</p>
  
  <p>I have a <code>RelayCommand</code> property and corresponding method that will start the program.</p>
  
  <p>Everything works if I explicitly create a <code>RelayCommand</code> for each button and call it in the Command directive in XAML but since I don't know how many buttons there will be, that is not an OK solution.</p>
  
  <p>My XAML looks like this:</p>
  
  <pre><code>&lt;ItemsControl ItemsSource="{Binding Buttons}"&gt;
      &lt;ItemsControl.ItemsPanel&gt;
          &lt;ItemsPanelTemplate&gt;
              &lt;WrapPanel/&gt;
          &lt;/ItemsPanelTemplate&gt;
      &lt;/ItemsControl.ItemsPanel&gt;
      &lt;ItemsControl.ItemTemplate&gt;
          &lt;DataTemplate&gt;
                  &lt;Button Content="{Binding Caption}" Height="30" Width="50" Margin="10" Command="{Binding DoSomething}" /&gt;
          &lt;/DataTemplate&gt;
      &lt;/ItemsControl.ItemTemplate&gt;
  
  &lt;/ItemsControl&gt;
  </code></pre>
  
  <p>The buttons are created fine, with the correct caption but the Command doesn't fire.</p>
  
  <p>How can I make this happen?</p>
  
  <p>Edit:</p>
  
  <pre><code> public class MainViewModel : ViewModelBase
  {
  
      public ObservableCollection&lt;ButtonDef&gt; Buttons { get; set; }
  
      public List&lt;DataItem&gt; Items { get; set; }
  
      public RelayCommand DoSomething { get; set; }
  
  
  
  
  
  
      /// &lt;summary&gt;
      /// Initializes a new instance of the MainViewModel class.
      /// &lt;/summary&gt;
      public MainViewModel(IDataService dataService)
      {
  
  
          Items = new List&lt;DataItem&gt; { new DataItem("Item 1"), new DataItem("Item 2") };
  
          //Items.Add(new DataItem("Item 1"));
  
          if (Buttons == null) Buttons = new ObservableCollection&lt;ButtonDef&gt;();
          foreach (var item in Items)
          {
              Buttons.Add(new ButtonDef
              {
                  Caption = item.Title,
                  Cmd = "Path to exe"
          });
      }
  
  
  }
  </code></pre>