0

我想做一个Country ComboBox ,我如何将此XML文件绑定到ComboBox,这是我的代码:

public class CountriesComboBox : ComboBox
{

    public CountriesComboBox()
    {
        XDocument obj = XDocument.Load("countries.xml");
        //DisplayMember = "countryiso";
        //ValueMember = "countrycode";
        DataSource = obj.Descendants("country").Select(x => new
        {
            countrycode = x.Attribute("code").Value,
            countryiso = x.Attribute("name").Value
        }).ToList();
    }

}

这是我的 XML 文件:

<countries>
  <country code="AF" iso="4">Afghanistan</country> 
  <country code="AL" iso="8">Albania</country> 
  <country code="DZ" iso="12">Algeria</country> 
  <country code="AS" iso="16">American Samoa</country> 
  <country code="AD" iso="20">Andorra</country> 
  <country code="AO" iso="24">Angola</country> ....
4

3 回答 3

0

I believe you're in the right track.

  1. Create a class that represents you Countries in the combobox: CountryView
  2. Put properties there: code, iso, name, etc...
  3. parse your xml like you're doing and create instances of CountryView.
  4. Set your datasource to your list
  5. Set the displayMember and displayValue accordingly: each to a property name in your class
  6. For better performance cache your list of countries (if they do not change which i guess it's a pretty immutable list)

From you question you're currently trying to bind to an anonymous type. I've never tried and i rather have a named-class for that need.

于 2013-10-18T09:57:33.307 回答
0

我正在为 WPF 做这件事。

comboBox1.ItemsSource = xdoc.Root.Descendants("country").Select(x => x.Value);
于 2013-10-18T10:09:50.433 回答
0

试试这个: -

public class CountriesComboBox : ComboBox
{

    public CountriesComboBox()
    {
        XDocument obj = XDocument.Load("countries.xml");
        //DisplayMember = "countryiso";
        //ValueMember = "countrycode";
        DataSource = obj.Descendants("country").Select(x => new
        {
            countrycode = x.Attribute("code").Value,
            countryiso = x.Attribute("iso").Value
        }).ToList();
    }

}

使用x.Attribute("iso").Value而不是x.Attribute("name").Value.

于 2013-10-18T10:00:56.270 回答