ListBox Data Binding Sample
How to get this code going:
- Create a Windows Presentation Foundation project named ListBoxSample
- Add a new class file named Computer.cs
- Paste the following code into the corresponding files.
Replace the contents of Window1.xaml with this:
<Window x:Class="ListBoxSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<DataTemplate x:Key="compTemplate">
<StackPanel>
<TextBlock FontSize="14" Text="{Binding Path=Name}" />
<TextBlock FontSize="10" Text="{Binding Path=Location}" />
<TextBlock FontSize="10" Text="{Binding Path=Make}" />
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid Name="mainGrid" Background="AntiqueWhite">
<ListBox Name="computerList" ItemTemplate="{StaticResource compTemplate}" Margin="0,0,0,29" />
<Button Height="23" Name="button1" VerticalAlignment="Bottom" Click="button1_Click">Pick me!</Button>
</Grid>
</Window>
Replace the contents of Window1.xaml.cs with this:
using System.Windows;
namespace ListBoxSample
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
computerList.ItemsSource = Computer.SampleComputers();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Computer selectedComputer = computerList.SelectedItem as Computer;
if (selectedComputer == null)
{
MessageBox.Show("Select something");
return;
}
MessageBox.Show("You have selected " + selectedComputer.Name);
}
}
}
Replace the contents of Computer.cs with this:
using System;
using System.Collections.Generic;
namespace ListBoxSample
{
public class Computer
{
public String Name { get; set; }
public string Location { get; set; }
public string Make { get; set; }
public Computer(String name, String location, String make)
{
Name = name;
Location = location;
Make = make;
}
public static IEnumerable<Computer> SampleComputers()
{
List<Computer> result = new List<Computer>();
result.Add(new Computer("Kitchen PC", "On the kitchen counter", "DELL AX443"));
result.Add(new Computer("NAS", "Network attached storage", "NSLU2"));
result.Add(new Computer("Media1", "Media server", "DELL VISTA"));
result.Add(new Computer("KidPC", "Kids play stuff", "HP1"));
result.Add(new Computer("XBOX360", "Playing more", "MS"));
return result;
}
}
}
Compile and run.
|