Programmatically selecting an Item in a ListBox

有些话、适合烂在心里 提交于 2021-01-28 21:55:53

问题


I have three ListBoxes (CompanyName, Representative & QuoteNumber) and I load data from my WCF client, into the CompanyName list box using the method below:

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.

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. 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.


回答1:


With data binding you can bind the ItemsSource and SelectedItem

Then you can just assign the SelectedItem in code behind
You most likely will need to implement INotifyPropertyChanged

And you can populate Representative with binding
But what you have is strange - you just keep added Represetatives with each SelectionChanged




回答2:


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.

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

Thanks for all the help dudes! :)



来源:https://stackoverflow.com/questions/31313773/programmatically-selecting-an-item-in-a-listbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!