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

本文关键字:取文本 Wpf 获取 组合 | 更新日期: 2023-09-27 17:52:50

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

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

<ComboBoxItem> Abc</ComboBoxItem>Content设置为Abc,因此您需要将SelectedItem转换为ComboBoxItem并获得该属性。

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

这将返回组合框中所选项的文本。

    string value = userType.Text.ToString();

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

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