简体   繁体   English

如何将组合框的选定值设置为字符串值

[英]How to set the selected value of a combobox to a string value

I've spent a while looking for an answer but I haven't found anything that has worked for me so far. 我已经花了一段时间寻找答案,但是到目前为止,我还没有发现任何对我有用的东西。 I have a system that saves the contents of a combobox to a database. 我有一个将组合框的内容保存到数据库的系统。 When I get the contents back from the database, I'm trying to set the selected item of the combobox to the item returned from the database. 当我从数据库取回内容时,我正在尝试将组合框的选定项设置为从数据库返回的项。 for example: XAML: 例如:XAML:

<ComboBox SelectedValuePath="Content" x:Name="cmbMyCmb" SelectedIndex="0" SelectionChanged="cmbMyCmb_SelectionChanged">
      <ComboBoxItem Content="Please Select"/>
      <ComboBoxItem Content="Item 1"/>
      <ComboBoxItem Content="Item 2"/>
      <ComboBoxItem Content="Item 3"/>
</ComboBox>

Code Behind: 背后的代码:

cmbMyCmb.SelectedValue = itemFromDatabase;

If I display the itemFromDatabase it shows "Item 2" and it is a string. 如果我显示itemFromDatabase它将显示“ Item 2”,它是一个字符串。

What I have on the form is an input form and a datagrid. 我在表单上拥有的是输入表单和数据网格。 When an item is selected from the datagrid I want the items to be displayed in the input form so they can be edited and updated. 从数据网格中选择一个项目后,我希望这些项目显示在输入表单中,以便可以对其进行编辑和更新。 I have all other items displaying I just need this combobox to set the selected value to the string from the database. 我还有其他所有显示项,我只需要此组合框即可将所选值设置为数据库中的字符串。

Get rid of SelectedIndex="0" in your combo definition and try this: 消除组合定义中的SelectedIndex="0" ,然后尝试以下操作:

 <ComboBox x:Name="cmbMyCmb" SelectedValuePath="Content" SelectionChanged="cmbMyCmb_SelectionChanged" Margin="99,104,117.4,157.8">
        <ComboBoxItem Content="Please Select"/>
        <ComboBoxItem Content="Item 1"/>
        <ComboBoxItem Content="Item 2"/>
        <ComboBoxItem Content="Item 3"/>
    </ComboBox>

Code behind: 后面的代码:

private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        //get item from database here
        string itemFromDatabase = "Item 2";

        cmbMyCmb.SelectedValue = itemFromDatabase;
    }

在此处输入图片说明

Note I'm doing it in the Loaded event as a sample on how to change. 请注意,我正在Loaded事件中进行操作,以作为有关如何更改的示例。 If you do it in SelectionChanged event, the result is that whatever the user selects, your code behind is going to put it back to whatever value you want, which doesn't make sense. 如果在SelectionChanged事件中执行此操作,则结果是无论用户选择什么,后面的代码都会将其恢复为所需的任何值,这没有任何意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM