Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

c# - Combobox get selected box item?

Here is my ComboBox and I want to check if the comboboxItem with the name="tweepersonen" gets selected to do something (WPF)

<ComboBox Name="AantalPersonenCombobox" Grid.Column="1" HorizontalAlignment="Left" Margin="88,155,0,0" VerticalAlignment="Top" Width="140" SelectionChanged="DropdownMenuNachten_SelectionChanged">
     <ComboBoxItem x:Name="tweePersonen" Content="2 Personen"/>
     <ComboBoxItem x:Name="driePersonen" Content="3 Personen"/>
     <ComboBoxItem x:Name="vierPersonen" Content="4 Personen"/>
</ComboBox>

c# Code:

private void AantalNachtenCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
      if(AantalNachtenCombobox.SelectionBoxItem == tweePersonen)
      {
           MessageBox.Show("Your Cheap");                   
      }               
 }
question from:https://stackoverflow.com/questions/65646846/combobox-get-selected-box-item

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The way you can access the ComboBoxItem to check if the Name matches, is by using the ItemContainerGenerator of the ComboBox:

private void DropdownMenuNachten_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var selectedItemContainer = AantalPersonenCombobox.ItemContainerGenerator.ContainerFromIndex(AantalPersonenCombobox.SelectedIndex) as ComboBoxItem;

    if (selectedItemContainer?.Name == "tweePersonen")
    {
        MessageBox.Show("Your Cheap");
    }
}

However, if you don't expect the ComboBoxItem content to change then it would be better to check for the content itself: AantalPersonenCombobox.SelectedItem == "2 Personen"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...