如何分配组合框中所选项目的值?

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 如果双击组合框,它将在 .xaml.cs 文件中自动生成 SelectionChanged 的代码。此外,在 .xaml 上,当您单击 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 添加到 ComboBox。尝试以编程方式将字符串添加为字符串,而不是 ComboBoxItems,看看是否有帮助。

如果你不想这样做,那么试试这个:

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

编辑:这将 select 与您输入的字符串内容相同的项目。

注意:您需要在 for

的顶部添加 using System.Linq;

希望对您有所帮助