title: Change DataGrid ItemsSource binding in code-behind
body: <p>I need to be able to change the binding of a DataGrid in the code-behind if the DataGrid does not have items within it, and vice versa.</p>
  
  <p>As it stands, here is what my current attempt looks like:</p>
  
  <p>C#:</p>
  
  <pre><code>List&lt;Character&gt; Characters = new List&lt;Character&gt;
              {
                  new Character("Judge Dredd", Gender.Male, CharacterClass.Fighter),
                  new Character("Princess Xena", Gender.Female, CharacterClass.Fighter),
                  new Character("Hawkeye", Gender.Male, CharacterClass.Ranger),
                  new Character("Laura Croft", Gender.Female, CharacterClass.Ranger),
                  new Character("Merlin", Gender.Male, CharacterClass.Mage),
                  new Character("Wicked Witch of the West", Gender.Female, CharacterClass.Mage)
  
              };
  
  HeroBox.ItemsSource = Characters;
  </code></pre>
  
  <p>WPF:</p>
  
  <pre><code>&lt;DataGrid x:Name="InvGrid"
            Background="DimGray"
            Grid.Column="1"
            ItemsSource="{Binding ElementName=HeroBox, Path=SelectedValue.Inventory}"
            AutoGenerateColumns="False"&gt;
      &lt;DataGrid.Columns&gt;
          &lt;DataGridCheckBoxColumn Header="Equip"
                                  Binding="{Binding Path=Equipped, Mode=TwoWay}"&gt;&lt;/DataGridCheckBoxColumn&gt;
          &lt;DataGridTextColumn Header="Name"
                              Binding="{Binding Path=Name, Mode=TwoWay}"&gt;&lt;/DataGridTextColumn&gt;
          &lt;DataGridTextColumn Header="Effect"
                              Binding="{Binding Path=Effect, Mode=TwoWay}"&gt;&lt;/DataGridTextColumn&gt;
          &lt;DataGridTextColumn Header="Cost"
                              Binding="{Binding Path=Cost, Mode=TwoWay}"&gt;&lt;/DataGridTextColumn&gt;
      &lt;/DataGrid.Columns&gt;
  &lt;/DataGrid&gt;
  </code></pre>
  
  <p>Attempt to change ItemsSource of InvGrid - includes compilation errors(C#):</p>
  
  <pre><code>if (InvGrid.Items.Count == 0)
  {
      Binding b = new Binding("HeroBox")
      {
          ElementName = "HeroBox",
          Path = "SelectedValue.Inventory"
      };
      InvGrid.ItemsSource = new Binding(b);
  } 
  else
  {
      InvGrid.ItemsSource = null;
  }
  </code></pre>
  
  <p>Essentially, I would like to achieve the same effect here: </p>
  
  <pre><code>ItemsSource="{Binding ElementName=HeroBox, Path=SelectedValue.Inventory}"
  </code></pre>
  
  <p>But in C#. </p>
  
  <p>The InvGrid DataGrid pulls its data from the Inventory of the selected hero from the ComboBox (HeroBox) which is randomly generated at runtime. Afterwards, the DataGrid should allow for the user to enter anything without automatically generating anything, yet at the moment the DataGrid randomly generates a new random item in the inventory, allowing the user to change it from there.</p>