How to display list of items.
In order to display a list of items we obviously need two things:
- a list of items
- some UI control prepared for the task of displaying lists
WPF is quite liberal about what can be our list of items. It can be a Collection or even IEnumerable. Of course it can work with more sophisticated types but more about it some other time.
When choosing a control we should know something about WPF Content Model idea. For our task best one will be a control implementing ItemsControl content model. When we’ve got our data and control the rest is easy. We just need to bind data to control and we do it like this:
Application instance like usually :
1: <Application2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"3: StartupUri="View/MainWindow.xaml"4: />
MainWindow that way:
1: <Window2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"4: x:Class="SimpleList.MainWindow"5: >6: <ListBox ItemsSource="{Binding Path=Numbers}"/>7: </Window>
1: using System.Collections.Generic;2: using System.Windows;3:4: namespace SimpleList5: {6: public partial class MainWindow : Window7: {8: public MainWindow()9: {10: InitializeComponent();11:12: Numbers = new List<int>();13:14: Numbers.Add(1);15: Numbers.Add(2);16: Numbers.Add(3);17:18: this.DataContext = this;19: }20:21: public IList<int> Numbers { get; set; }22: }23: }
Important things we should remember are:
- Content Model idea
- DataContext dependency property provided by FrameworkContentElement
- the whole data binding mechanism
- the fact that we can define part of a class as partial class and e.g. set DataContext property that way
Advertisement
Leave a Comment