简体   繁体   English

在 WPF 中设置 combobox 上的选定值

[英]Set Selected value on combobox in WPF

I have a simple WPF with a combobox;我有一个简单的 WPF 和一个 combobox; when I use new array as itemssource (COMMENTED LINE IN CODE), I can set the default value by setting SelectedValue="..." (a string from another query result. but when I use a query and reading from DB. adding items works, but the setting SelectedValue job does not work!当我使用新数组作为项目源(代码中的注释行)时,我可以通过设置SelectedValue="..." (来自另一个查询结果的字符串。但是当我使用查询并从数据库读取时。添加项目有效,但设置SelectedValue作业不起作用!

my xaml.cs code:我的xaml.cs代码:

tempdbEntities mydb = new tempdbEntities();
public MainWindow()
{
    InitializeComponent();
    FillForm(1);
}

private void Window_Activated(object sender, EventArgs e)
{
    //cmbVendors.ItemsSource = new string[] { "ABC", "BCD", "EFG" };

    cmbVendors.ItemsSource = mydb.tbl_Company.Where(c => c.Id < 5).ToList();
    cmbVendors.DisplayMemberPath = "Name";    
}

private void FillForm(int ID0)
{    
    cmbVendors.SelectedValue = mydb.tbl_Company.Where(c => c.Id == ID0).Single().Name;    
}

Xaml code: Xaml 代码:

<Grid Margin="0,-41,0,0">
    <ComboBox Name="cmbVendors" HorizontalAlignment="Left" 
              Margin="474,102,0,0" VerticalAlignment="Top" 
              Width="231"/>    
</Grid>

Combobox's DisplayMemberPath will just control what need to be displayed; Combobox 的DisplayMemberPath将只控制需要显示的内容; SelectedValue will be still of your Model type. SelectedValue仍然是您的Model类型。 You need to set你需要设置

cmbVendors.SelectedValuePath = "Name";

This will make sure your cmbVendors 's SelectedValue will hold Name .这将确保您的cmbVendorsSelectedValue将持有Name

what I want to do: this is an edit form.我想要做什么:这是一个编辑表单。 when the form is loaded, should fill all components in form, textboxes,comboboxes,... by data from table.加载表单时,应通过表格中的数据填充表单、文本框、组合框...中的所有组件。 cmbVendors like other components should show the content got from DB, and if user wanted to change it, he can do. cmbVendors 和其他组件一样应该显示从 DB 获取的内容,如果用户想更改它,他可以做到。 and click submit....然后点击提交......

I have edited the FillForm Method as bellow:我已经编辑了 FillForm 方法,如下所示:

private void FillForm(int ID0)
        {
            cmbVendors.SelectedValuePath = "Name";
            cmbVendors.SelectedValue = mydb.tbl_Company.Where(c => c.Id == ID0).Single().Name;

        }

Thanks.谢谢。 It works well!它运作良好!

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

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