#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 .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: