簡體   English   中英

如何從組合框C#WPF中獲取文本?

[英]How to get text from Combo box c# Wpf?

每當我嘗試從組合框中獲取文本時,它都會提取System.Windows.Controls.ComboBoxItem: Abc數據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);

您的努力將不勝感激:)。

謝謝,

    <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 ,因此您需要將SelectedItemComboBoxItem並獲取該屬性。

(XAML設置內容可以在基類ContentControl看到,該基類具有一個ContentPropertyAttribute ,用於定義要設置的屬性。)

您可以獲得項目的內容:

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

這將返回ComboBox中所選項目的文本。

    string value = userType.Text.ToString();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM