Another old and faithful control that has made the transition to WPF is the ListBox. It’s pretty simple to create a ListBox, and load some values into it.
<ListBox>
<ListBoxItem>Item 1</ListBoxItem>
<ListBoxItem>Item 2</ListBoxItem>
<ListBoxItem>Item 3</ListBoxItem>
</ListBox>
Of course the ListBox isn’t much good if you can’t get the value out of it. To do that we’ll have to add a few things.
<Button Name=“ShowSelected“ Click=“ShowSelected_Click“>Show Selected</Button>
<ListBox Name=“lbxDemo“>
<ListBoxItem>Item 1</ListBoxItem>
<ListBoxItem>Item 2</ListBoxItem>
<ListBoxItem>Item 3</ListBoxItem>
</ListBox>
Here I added a button that would show which item was selected, then I had to give the ListBox a name we could refer to. Following techniques I’ve previously laid out (http://arcanecode.wordpress.com/2007/09/07/adding-wpf-controls-progrrammatically/) I added a click event for the button.
Now, you might think you could just enter something like
MessageBox.Show(“You Selected “ + lbxDemo.SelectedValue);
And get a message back. But instead what you get is:
This is because the SelectedValue is actually a ListBoxItem, and not a value. Instead you need to get the content of the ListBoxItem thusly:
ListBoxItem lbi = (lbxDemo.SelectedItem as ListBoxItem);
MessageBox.Show(“You REALLY selected “ + lbi.Content.ToString());
Now you’ll see:
Note that you’re not just restricted to ListBoxItems. I could, for example use checkboxes:
<ListBox Name=“lbxCheckMe“>
<CheckBox>Item 1</CheckBox>
<CheckBox>Item 2</CheckBox>
<CheckBox>Item 3</CheckBox>
<CheckBox>Item 4</CheckBox>
</ListBox>
Like other controls, you can stack other controls inside the contents of a ListBoxItem. Let’s get a little fancy, and create a list box with both text and images.
<ListBox Name=“lbxCool“>
<ListBoxItem>
<StackPanel Orientation=“Horizontal“>
<TextBlock Width=“100“>Anna</TextBlock>
<Image Source=“D:\Presentations\100Anna.jpg“ Height=“100“ />
</StackPanel>
</ListBoxItem>
<ListBoxItem>
<StackPanel Orientation=“Horizontal“>
<TextBlock Width=“100“>Raven</TextBlock>
<Image Source=“D:\Presentations\100Rave.jpg“ Height=“100“ />
</StackPanel>
</ListBoxItem>
<ListBoxItem>
<StackPanel Orientation=“Horizontal“>
<TextBlock Width=“100“>Ammie</TextBlock>
<Image Source=“D:\Presentations\100Ammie.jpg“ Height=“100“ />
</StackPanel>
</ListBoxItem>
<ListBoxItem>
<StackPanel Orientation=“Horizontal“>
<TextBlock Width=“100“>Kids</TextBlock>
<Image Source=“D:\Presentations\100Kids.jpg“ Height=“100“ />
</StackPanel>
</ListBoxItem>
</ListBox>
</StackPanel>
(Note you can use any images, I used a few of my kids and wife.) The result is this:
This covers some basics on using a ListBox, enough to get you started with your own lists.
