2016-05-28 39 views
1

我想獲得國家的名字形成列表中的一個領域,並把他們的組合框:WCF - 列表組合框

public TravelAgencyResponse GetInformation(TravelAgencyRequest request) 
    { 
     TravelAgencyResponse response = new TravelAgencyResponse(); 
     // response.Offers = new OfferDto(); 
     response.Offers = new List<DataTransferObjects.OfferDto>();    
     response.Offers.Add(new DataTransferObjects.OfferDto() 
     { 
      IdOffer = 0, 
      KindOfAccommodation = "Hotel", 
      Country = "Spain", 
     }); 

     response.Offers.Add(new DataTransferObjects.OfferDto() 
     { 
      IdOffer = 1, 
      KindOfAccommodation = "Hotel", 
      Country = "Italy", 
     }); 

     response.ThisOffer = (from offer in response.Offers 
           where offer.Country == request.Country 
           select offer).FirstOrDefault(); 
     return response; 
    } 

我認爲我可以使用LINQ沒有FirstOrDefault()但我在這種情況下不能這樣做。

private void button1_Click(object sender, EventArgs e) 
    { 
     Uri baseAddr = new Uri("http://localhost:1232/TravelAgencyService/SimpleTravelAgencyService/"); 
     ChannelFactory<ITravelAgencyService> factory = new ChannelFactory<ITravelAgencyService>(new WSHttpBinding(), 
      new EndpointAddress(baseAddr)); 
     ITravelAgencyService proxy = factory.CreateChannel(); 
     var response = proxy.GetInformation(
      new TravelAgencyService.Messages.TravelAgencyRequest() 
      { 
       Country = textBox1.Text 
      }); 

     comboBox1.Items.Add(response.ThisOffer.Country); 
     listBox1.Items.Add(response.ThisOffer.Country); 

    } 

我試圖把這些信息組合框那樣:

comboBox1.Items.Add(response.ThisOffer.Country); 

,我只給出了第一個國家或類似的:

comboBox1.Items.Add(response); 

,我沒有得到任何東西。

我與WCF的第一步!請理解,請!

回答

1

所以,如果我正確理解你的問題,你想要填寫任何response.OffersCountry屬性中包含的所有國家的ComboBox,是否正確?

既然你提到你是WPF的新手,那麼我將跳過關於MVVM and DataBinding的部分,並告訴你可以用你現在擁有的東西來完成。

首先,您需要從Offers中「提取」所有國家,最好只進行一次並按字母順序排序。

List<string> countries = response.Offers 
    .Select(o => o.Country) // We only need the "Country" of the offer 
    .Distinct()    // Every country only once 
    .OrderBy(c => c)  // Sort by name 
    .ToList();    // make a List<string> out of it 

而是手動添加的項目,我建議賦予所有的人一下子,通過設置DataSource財產。

comboBox1.DataSource= countries; 

你需要確保然而這Items是空的,手動添加的項目和DataSource沒有很好地協同工作。

如果要預先選擇某個國家(例如從ThisOffer一個),你可以設置ComboBox的SelectedItem屬性:

comboBox1.SelectedItem = response.ThisOffer.Country; 
+0

但我不能使用List 我的數據 - _ error不能將類型'System.Linq.IOrderedEnumerable '隱式轉換爲'System.Collections.Generic.List '。存在明確的轉換(您是否缺少演員?)_ 而且我得到ComboBox不包含_ItemsSource_的定義的信息,_DataSource_是否一樣? – Quicki

+0

@KlaudiaW。我更新了語句,你也需要調用'ToList',至於'ComboBox'不包含ItemsSource的定義:我認爲你使用的是WPF,我的錯誤。是的,你應該可以使用'DataSource',我會更新答案。 –