How do i get the text value from a ComboBox in WPF?

后端 未结 2 1337
一整个雨季
一整个雨季 2021-01-02 15:45

This may be something covered in C# 101 but I haven\'t been able to find an easy to understand answer to this question anywhere on google or stack overflow. Is there a bett

相关标签:
2条回答
  • 2021-01-02 16:25

    It looks like you have ComboBoxItems in your ComboBox, so that SelectedValue is returning a ComboBoxItem and ToString is therefore returning something like ComboBox SomeValue.

    If that's the case, you can get the content using ComboBoxItem.Content:

    ComboBoxItem selectedItem = (ComboBoxItem)(test_site.SelectedValue);
    string value = (string)(selectedItem.Content);
    

    However, a better approach is, instead of populating the ComboBox with a collection of ComboBoxItems, to set ComboBox.ItemsSource to the desired collection of strings:

    test_site.ItemsSource = new string[] { "Alice", "Bob", "Carol" };
    

    Then SelectedItem will get you the currently selected string directly.

    string selectedItem = (string)(test_site.SelectedItem);
    
    0 讨论(0)
  • 2021-01-02 16:35

    On load events put

    DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(ComboBox.TextProperty, typeof(ComboBox));
    
    dpd.AddValueChanged(cmbChungChi, OnTextChanged);
    

    And get text via funtion

    private void OnTextChanged(object sender, EventArgs args)
    {
        txtName.Text = cmbChungChi.Text;
    } 
    

    Good luck.

    0 讨论(0)
提交回复
热议问题