如何从组合框c#Wpf获取文本?

时间:2016-06-27 17:38:40

标签: c# wpf xaml

每当我尝试从组合框中获取文本时,它都会提取System.Windows.Controls.ComboBoxItem: Abc

等数据

我怎样才能获得" Abc" ?我的意思是说只有值而不是整个堆栈跟踪。 我的代码似乎是: -

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);

您的努力将不胜感激:)。

谢谢,

4 个答案:

答案 0 :(得分:2)

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

然后在代码背后:

    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);
            }
        }
    }

答案 1 :(得分:1)

<ComboBoxItem> Abc</ComboBoxItem>Content设置为Abc,因此您需要将SelectedItem投放到ComboBoxItem并获取该属性。

(XAML设置的内容可以显示在基类ContentControl中,其中ContentPropertyAttribute定义了要设置的属性。)

答案 2 :(得分:1)

您可以获取该项目的内容:

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

答案 3 :(得分:1)

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

    string value = userType.Text.ToString();