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.
As it stands, here is what my current attempt looks like:
C#:
List<Character> Characters = new List<Character>
{
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;
WPF:
<DataGrid x:Name="InvGrid"
Background="DimGray"
Grid.Column="1"
ItemsSource="{Binding ElementName=HeroBox, Path=SelectedValue.Inventory}"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridCheckBoxColumn Header="Equip"
Binding="{Binding Path=Equipped, Mode=TwoWay}"></DataGridCheckBoxColumn>
<DataGridTextColumn Header="Name"
Binding="{Binding Path=Name, Mode=TwoWay}"></DataGridTextColumn>
<DataGridTextColumn Header="Effect"
Binding="{Binding Path=Effect, Mode=TwoWay}"></DataGridTextColumn>
<DataGridTextColumn Header="Cost"
Binding="{Binding Path=Cost, Mode=TwoWay}"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
Attempt to change ItemsSource of InvGrid - includes compilation errors(C#):
if (InvGrid.Items.Count == 0)
{
Binding b = new Binding("HeroBox")
{
ElementName = "HeroBox",
Path = "SelectedValue.Inventory"
};
InvGrid.ItemsSource = new Binding(b);
}
else
{
InvGrid.ItemsSource = null;
}
Essentially, I would like to achieve the same effect here:
ItemsSource="{Binding ElementName=HeroBox, Path=SelectedValue.Inventory}"
But in C#.
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.