简体   繁体   中英

SelectionChanged Combobox WPF

I want to populate a ComboBox based on selection of other ComboBox . Both combo boxes are populate from database using WCF. My problem is that on first selection it's not working (just after second selection it's work and it's show results from first selection).

XAML

<ComboBox 
   x:Name="selClientCombo" 
   SelectionChanged="listEchipamente" 
   IsEditable="True" 
   SelectedIndex="-1" 
   HorizontalAlignment="Left" 
   Margin="455,35,0,0" 
   VerticalAlignment="Top" 
   Width="215" 
   ItemsSource="{Binding Mode=OneWay}"/>
<ComboBox 
   x:Name="selEchipamentCombo" 
   HorizontalAlignment="Left" 
   Margin="457,65,0,0" 
   VerticalAlignment="Top" 
   Width="213" 
   ItemsSource="{Binding}"/>

code

  private void listEchipamente(object sender, SelectionChangedEventArgs e)
        {
            List<string> echipamenteWCF = client.getEchipament(selClientCombo.Text).ToList();

            MessageBox.Show(" Client Selected !");
            if (selEchipamentCombo.Items.Count >0)
            {
                selEchipamentCombo.Items.Clear();
            }
                for (int i = 0; i < echipamenteWCF.Count(); i++)
                {
                    selEchipamentCombo.Items.Add(echipamenteWCF[i]);
                }

            }

At the time SelectionChanged is fired, the Text has not been updated (and hence it holds the previous value).

You should access the underlying data item to get the Text instead:

if(selClientCombo.SelectedItem == null) return;
List<string> echipamenteWCF = 
                   client.getEchipament(selClientComo.SelectedItem.ToString()).ToList();
...

I supposed the ToString() will resolve the display Text. You can always cast SelectedItem to the actual type and access its string property (being shown as Text) easily. You can also access the SelectedValue with condition that some SelectedValuePath is set for the ComboBox.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM