Software & Finance





Visual Studio.NET WPF - ListBox Binding ItemTemplate / DataTemplate





List Box Control is named as MyListBox1.  If you see the XAML code, under ListBox.ItemTemplate, TextBlock control has a binding with CityName.


<TextBlock Grid.Column="0" Text="{Binding CityName}"/>


At run time,
List<CMyData> arrayCity = new List<CMyData>(); is assigned with MyListBox1.ItemsSource = arrayCity;

The important thing here is the class name CMyData has a string member variable called CityName. This member variable name must match the name given in the Binding Property under xaml file.

Look at the code xaml and .cs given below:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

 

namespace ListBoxAddItem

{

    /// <summary>

    /// Interaction logic for MainWindow.xaml

    /// </summary>

    ///

 

    public class CMyData

    {

        public string CityName { get; set; }

    }

 

    public partial class MainWindow : Window

    {

        List<CMyData> arrayCity = new List<CMyData>();

 

        public MainWindow()

        {

            InitializeComponent();

           

            arrayCity.Add(new CMyData() { CityName = "Chennai" });

            arrayCity.Add(new CMyData() { CityName = "Mumbai" });

            arrayCity.Add(new CMyData() { CityName = "Hyderabad" });

            arrayCity.Add(new CMyData() { CityName = "New York" });

            arrayCity.Add(new CMyData() { CityName = "San Jose" });

            MyListBox1.ItemsSource = arrayCity;

        }

    }

}

 

<Window x:Class="ListBoxAddItem.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="MainWindow" Height="200" Width="225" >

 

   

    <Grid x:Name="mainGrid">

        <StackPanel Orientation="Vertical" Margin="0,10,0,0">

           

           

        <ListBox Name="MyListBox1" Height="100" HorizontalAlignment="Center"

                 Margin="5,10,5,0" VerticalAlignment="Top" Width="150"

                 >

                <ListBox.ItemTemplate>

                    <DataTemplate>

                        <Grid>

                            <Grid.ColumnDefinitions>

                                <ColumnDefinition Width="50" />

                            </Grid.ColumnDefinitions>

                            <TextBlock Grid.Column="0" Text="{Binding CityName}"/>

                        </Grid>

                    </DataTemplate>

                </ListBox.ItemTemplate>

 

            </ListBox>

        </StackPanel>

    </Grid>

</Window>