【问题标题】:How to get text from Combo box c# Wpf?如何从组合框 c# Wpf 中获取文本?
【发布时间】:2016-10-29 19:47:29
【问题描述】:

每当我尝试从组合框中获取文本时,它都会提取像 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);

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

谢谢,

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:
        <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);
                }
            }
        }
    

    【讨论】:

    【解决方案2】:

    &lt;ComboBoxItem&gt; Abc&lt;/ComboBoxItem&gt;Content 设置为Abc,因此您需要将SelectedItem 转换为ComboBoxItem 并获取该属性。

    (XAML 设置内容可以在基类ContentControl 中看到,它有一个ContentPropertyAttribute 定义要设置的属性。)

    【讨论】:

    • 没有成功:(。请你准备一个 XAML 和 C# 代码。这对我真的很有帮助:)
    • 这和 KipMorgan 写的差不多,只是你应该使用as,而应该使用(ComboBoxItem)userType.SelectedItem,等等。
    • 它有效,实际上我尝试过这样的事情:- var value = userType.SelectionBoxItem.ToString();它奏效了。谢谢你们的努力。
    • 另外:建议查看data binding
    • @H.B.啊,我明白了—— InvalidCastException 比 NullReferenceException 提供更多信息。谢谢。
    【解决方案3】:

    这应该返回组合框中所选项目的文本。

        string value = userType.Text.ToString();
    

    【讨论】:

    【解决方案4】:

    可以获取item的内容:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多