I am developing a WPF user control library in C#. The library has a form where the user interacts. The form has 3 comboboxes (ComboBox1, ComboBox2 and ComboBox3). Once user selects the item in combobox1, then the combobox 2 and 3 will show items that will go with the user selection. The way I have this setup is:
xaml:
<ComboBox Grid.Column="1" Grid.ColumnSpan="2" x:Name="cmbBox_TubeType_SlabUserCtrl" Height="auto" SelectionChanged="cmbBox1_SelectedIndexChanged" x:FieldModifier="public">
<ComboBoxItem>Item1</ComboBoxItem>
<ComboBoxItem>Item2</ComboBoxItem>
<ComboBoxItem>Item3</ComboBoxItem>
</ComboBox>
C#
if (this.cmbBox1.SelectedIndex == 0)
{
this.cmbBox2.ItemsSource = new object[] { "B01", "B02" };
this.cmbBox3.ItemsSource = new object[] { "J01", "J22" };
}
else if (this.cmbBox1.SelectedIndex == 1)
{
this.cmbBox2.ItemsSource = new object[] { "B21", "B22" };
this.cmbBox3.ItemsSource = new object[] { "J21", "J32" };
}
else if (this.cmbBox1.SelectedIndex == 2)
{
this.cmbBox2.ItemsSource = new object[] { "B31", "B32" };
this.cmbBox3.ItemsSource = new object[] { "J21", "J32" };
}
With this setup, I then have this line which seems to give me trouble:
string cmb1TypeString = cmbBox1.SelectedItem.ToString();
When I run this cmb1TypeString is set as null. However, when I look into the class values during debug it appears it has the right value.
While trying other things, I took out the initialization of combobox items for Combobox1 from xaml. Instead I put the initialization of items right after the InitializeComponent() of class definition as follows:
this.cmbBox1.ItemsSource = new object[] { "Item1", "Item2","Item3"};
With this change the Cmb1TypeString is returned correctly as the user selected value. I am not sure why this is happening? Is there any difference between how the combobox items are treated if they are set in xaml and the code?
Help is greatly appreciated.