#958 – Three Ways to Populate a List Control

There are three general ways that you can populate a list-based control with some content:

  • Add items in XAML
  • Add items in code
  • Use data binding  (preferred method, most flexible)

For example, to add several items to a ListBox from XAML:

    <ListBox>
        <ListBoxItem>Augustus</ListBoxItem>
        <ListBoxItem>Tiberius</ListBoxItem>
        <ListBoxItem>Caligula</ListBoxItem>
    </ListBox>

To add the same items from code:

    <ListBox Name="lbMyListBox"/>

 

            lbMyListBox.Items.Add("Augustus");
            lbMyListBox.Items.Add("Tiberius");
            lbMyListBox.Items.Add("Caligula");

Finally, to use data binding to add the items:

    <ListBox ItemsSource="{Binding Emperors}"/>

 

    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private string[] emperors;
        public string[] Emperors
        {
            get { return emperors; }
            set
            {
                if (value != emperors)
                {
                    emperors = value;
                    RaisePropertyChanged("Emperors");
                }
            }
        }

        public MainWindow()
        {
            this.InitializeComponent();
            this.DataContext = this;

            Emperors = new string[]
                {"Augustus",
                 "Tiberius",
                 "Caligula"};
        }

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        private void RaisePropertyChanged(string propName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }

958-001

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #958 – Three Ways to Populate a List Control

  1. Pingback: Dew Drop – November 26, 2013 (#1672) | Morning Dew

Leave a comment