简体   繁体   English

以编程方式在列表框中选择一个项目

[英]Programmatically selecting an Item in a ListBox

I have three ListBoxes ( CompanyName , Representative & QuoteNumber ) and I load data from my WCF client, into the CompanyName list box using the method below: 我有三个ListBoxesCompanyNameRepresentativeQuoteNumber ),并使用以下方法从WCF客户端将数据加载到CompanyName列表框中:

private async Task LoadCompanies()
{
    using (TruckServiceClient client = new TruckServiceClient())
    {
        var companies = await client.GetCompaniesAsync();
        foreach (var company in companies)
            lbxCompanyName.Items.Add(new ListBoxViewItem<Company>(company));
    }
}

Now in the coding below I allow myself to select the Company Name in the lbxCompanyName ListBox and then viewing the Representatives that belongs to that Company in my lbxRepresentative ListBox. 现在,在下面的代码中,我允许我自己在lbxCompanyName列表框中选择公司名称 ,然后在我的lbxRepresentative列表lbxRepresentative查看属于该公司的代表

private void lbxCompanyName_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var company = (ListBoxViewItem<Company>)lbxCompanyName.SelectedItem; //Changing this line to auto select an Item for me
    foreach (var rep in company.Item.Represetatives)
        lbxRepresentatives.Items.Add(new ListBoxViewItem<Represetative>(rep));
} 

What I want to achieve is to auto/programmatically select the name, let's say "Josh", from the CompanyName ListBox. 我要实现的是从CompanyName ListBox中自动/以编程方式选择名称,例如“ Josh”。 How would I go about doing this with the coding that I have now? 我将如何使用现在的编码进行操作?

Basically I want to hide my listboxes and let my program select everything for me. 基本上,我想隐藏我的列表框,然后让程序为我选择所有内容。

With data binding you can bind the ItemsSource and SelectedItem 使用数据绑定,您可以绑定ItemsSource和SelectedItem

Then you can just assign the SelectedItem in code behind 然后,您可以在后面的代码中分配SelectedItem
You most likely will need to implement INotifyPropertyChanged 您最有可能需要实现INotifyPropertyChanged

And you can populate Representative with binding 您可以用绑定填充代表
But what you have is strange - you just keep added Represetatives with each SelectionChanged 但是您拥有的东西很奇怪-您只需在每个SelectionChanged中添加添加的代表剂

For testing purposes I solved my issue by setting my first two ListBoxes (CompanyName, Representative) SelectedIndex to 0 and then using the coding below for my last ListBox (QuoteNumber) to select the last inserted row in my QuoteNumber listbox. 出于测试目的,我通过将前两个ListBox(CompanyName,代表) SelectedIndex为0,然后对下面的最后一个ListBox(QuoteNumber)使用下面的编码来选择QuoteNumber列表框中最后插入的行,从而解决了问题。

    if (lbxQuoteNumber.Items.Count > -1)
        lbxQuoteNumber.SelectedIndex = lbxQuoteNumber.Items.Count - 1;

Thanks for all the help dudes! 感谢所有帮助家伙! :) :)

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

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