简体   繁体   中英

How to get text from Combo box c# Wpf?

Whenever I'm trying to get text from combo box it extracts data like System.Windows.Controls.ComboBoxItem: Abc

How can I get only "Abc" ? I mean to say only value not entire stack trace. my code seems like:-

XAML:-

  <StackPanel Orientation="Horizontal" Width="auto" HorizontalAlignment="Center" Margin="0,10,0,0">
            <TextBlock HorizontalAlignment="Left" FontFamily="/Vegomart;component/Images/#My type of font" Text="User Type:- " FontSize="18" Foreground="Black"/>
            <ComboBox x:Name="userType" HorizontalAlignment="Right" FontFamily="/Vegomart;component/Images/#My type of font" Width="170" FontSize="18" Foreground="Black" Margin="40,0,0,0"  >
                <ComboBoxItem> Abc</ComboBoxItem>
            </ComboBox>
        </StackPanel>

C#:-

string value = userType.SelectedItem.ToString();
System.Diagnostics.Debug.WriteLine(value);

Your effort will be appreciated :).

Thanks,

    <ComboBox x:Name="userType" SelectionChanged="userType_SelectionChanged">
        <ComboBoxItem Content="Abc"/>
        <ComboBoxItem>Bcd</ComboBoxItem>
    </ComboBox>

Then in code behind:

    private void userType_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var comboBox = sender as ComboBox;
        if (comboBox != null)
        {
            var comboBoxItem = comboBox.SelectedItem as ComboBoxItem;
            if (comboBoxItem != null)
            {
                var content = comboBoxItem.Content;
                System.Diagnostics.Debug.WriteLine(content);
            }
        }
    }

<ComboBoxItem> Abc</ComboBoxItem> sets the Content to Abc , so you would need to cast your SelectedItem to ComboBoxItem and get that property.

(That the XAML sets the content can be seem in the base class ContentControl which has a ContentPropertyAttribute that defines which property to set.)

You can get the content of the item:

ComboBoxItem item = (ComboBoxItem)userType.SelectedItem;
string value = (string)item.Content;
System.Diagnostics.Debug.WriteLine(value);

这将返回ComboBox中所选项目的文本。

    string value = userType.Text.ToString();

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