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

时间:2015-10-07 11:03:01

标签: c# wpf xaml combobox datagrid

我花了一段时间寻找答案,但到目前为止我还没有发现任何对我有用的东西。我有一个系统,可以将组合框的内容保存到数据库中。当我从数据库中获取内容时,我试图将组合框的选定项目设置为从数据库返回的项目。例如: 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>

代码背后:

cmbMyCmb.SelectedValue = itemFromDatabase;

如果我显示itemFromDatabase它显示&#34;项目2&#34;它是一个字符串。

我在表单上的内容是输入表单和数据网格。当从数据网格中选择一个项目时,我希望项目在输入表单中显示,以便可以编辑和更新它们。我有所有其他项目显示我只需要这个组合框将所选值设置为数据库中的字符串。

1 个答案:

答案 0 :(得分:0)

在你的组合定义中删除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>

代码背后:

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

        cmbMyCmb.SelectedValue = itemFromDatabase;
    }

enter image description here

注意我在Loaded事件中这样做,作为如何更改的示例。如果你在SelectionChanged事件中执行此操作,结果是无论用户选择什么,您的代码都会将其恢复为您想要的任何值,这是没有意义的。