簡體   English   中英

如何分配組合框中所選項目的值?

[英]How can I assign the value of a selected item in a combobox?

我有一個已經包含默認值的組合框,我想為組合框分配一個值,以便在運行時,分配的值顯示為選中狀態。

這是組合框

<ComboBox x:Name="MyComboBox" VerticalAlignment="Center" Width="50" Padding="1" Height="23">
     <ComboBoxItem IsSelected="True">A</ComboBoxItem>
     <ComboBoxItem>B</ComboBoxItem>
     <ComboBoxItem>C</ComboBoxItem>
     <ComboBoxItem>D</ComboBoxItem>
     <ComboBoxItem>E</ComboBoxItem>
     <ComboBoxItem>F</ComboBoxItem>
     <ComboBoxItem>G</ComboBoxItem>
     <ComboBoxItem>H</ComboBoxItem>
     <ComboBoxItem>I</ComboBoxItem>
     <ComboBoxItem>K</ComboBoxItem>
     <ComboBoxItem>L</ComboBoxItem>
     <ComboBoxItem>M</ComboBoxItem>
     <ComboBoxItem>N</ComboBoxItem>
</ComboBox>

我分配的值將是默認值之一。 因此,我不想添加新項目。 只是為了顯示我已分配為選定的項目。

這是我嘗試沒有成功的方法:

//I get a value from reading a datareader

string MyValue = datareader.GetString(0);

// I assign the value to the combobox:

MyComboBox.SelectedItem = MyValue; //Attempt 1

MyComboBox.SelectedValue = MyValue; //Attempt 2

MyComboBox.Text= MyValue; //Attempt 3

MyComboBox.SelectedIndex = MyValue; //Attempt 4. Throws an error as MyValue is a string

謝謝你的幫助!

你有沒有試過這個方法:

使用 Visual Studio,在設計視圖或.xaml如果您雙擊 ComboBox,它將自動生成.xaml.cs文件中SelectionChanged代碼。 此外,在.xaml ,當您單擊 ComboBox 時,它會告訴您屬性選項卡上的對象名稱。 在這個例子中我的是comboBox:

private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string selectedItem = comboBox.Items[comboBox.SelectedIndex].ToString();
    Console.WriteLine(selectedItem);
}

為簡單起見,我只是將它打印到控制台,當您退出程序時會顯示出來。

因此,無論出於何種原因,要在運行時更改組合框中顯示的內容的值,您都可以使用以下內容:

comboBox.SelectedItem = comboBox.Items[0];

每當用戶進行任何選擇時,這會將其設置為您添加到組合框的第一個項目。

據我了解,您需要將文本分配給 ComboBox 中已有的項目:

string MyValue = "asd";
comboBox.Items.Add(MyValue);
comboBox.Text = MyValue;

我認為這不起作用,因為您將ComboBoxItem s 添加到您的ComboBox 嘗試以編程方式將字符串添加為字符串,而不是 ComboBoxItems,看看是否有幫助。

如果您不想這樣做,請嘗試以下操作:

MyComboBox.SelectedItem = MyComboBox.Items.Select(i => i as ComboBoxItem).FirstOrDefault(i => (i.Content as string) == "The string you want to select");

編輯:這將選擇與您輸入的字符串具有相同內容的項目。

注意:需要using System.Linq;添加using System.Linq; 到 for 的頂部

希望有幫助

暫無
暫無

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

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