先从最容易的开始演示ListBox控件的创建。
Adding ListBox Items
下面的代码是向ListBox控件中添加多项ListBoxItem集合。XAML代码如下:
<ListBox Margin="10,10,0,13" Name="listBox1" HorizontalAlignment="Left"
VerticalAlignment="Top" Width="194" Height="200">
<ListBoxItem Content="Coffie"></ListBoxItem>
<ListBoxItem Content="Tea"></ListBoxItem>
<ListBoxItem Content="Orange Juice"></ListBoxItem>
<ListBoxItem Content="Milk"></ListBoxItem>
<ListBoxItem Content="Iced Tea"></ListBoxItem>
<ListBoxItem Content="Mango Shake"></ListBoxItem>
</ListBox>
运行后的界面如图 Figure 1:
Figure 1
Adding ListBox Items Dynamically
动态添加ListBox集合项。用一个文本框,一个按钮。当点击添加按钮向ListBox控件中添加用法输入文本框的值。XAML代码如下:
<TextBox Height="23" HorizontalAlignment="Left" Margin="8,14,0,0"
Name="textBox1" VerticalAlignment="Top" Width="127" />
<Button Height="23" Margin="140,14,0,0" Name="button1" VerticalAlignment="Top"
HorizontalAlignment="Left" Width="76" Click="button1_Click">
Add Item
</Button>
运行后的界面如图Figure 2:
Figure 2
Button按钮的后台事件代码如下:
private void button1_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Add(textBox1.Text);
}
当点击添加按钮,用户输入文本框的值,就会显示到ListBox中。界面如图Figure 3:
Figure 3
Deleting ListBox Items
我们可以用ListBox.Items.Remove 或者 ListBox.Items.RemoveAt方法移除ListBox集合中的一项。RemoveAt 方法是用集合中的下标。
在XAML 代码中添加一个移除的按钮,代码如下:
<Button Height="23" Margin="226,14,124,0" Name="DeleteButton" VerticalAlignment="Top" Click="DeleteButton_Click">
Delete Item</Button>
按钮事件中写移除的逻辑。
private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.RemoveAt
(listBox1.Items.IndexOf(listBox1.SelectedItem));
}
Formatting and Styling
Formatting ListBox Items
格式ListBox项,设置ListBoxItem项的前景色和背景色。XAML中的代码如下:
<ListBoxItem Background="LightCoral" Foreground="Red" Content="Coffie"></ListBoxItem>
我们也可以设置ListBoxItem的字体样式。
<ListBoxItem Background="LightCoral" Foreground="Red" Content="Coffie" FontFamily="Verdana" FontSize="12"
FontWeight="Bold"></ListBoxItem>
现在来统一设置一下ListBoxItems的属性:
<ListBoxItem Background="LightCoral" Foreground="Red" Content="Coffie" FontFamily="Verdana" FontSize="12"
FontWeight="Bold"></ListBoxItem>
<ListBoxItem Background="LightGray" Foreground="Black" Content="Tea" FontFamily="Georgia" FontSize="14"
FontWeight="Bold"></ListBoxItem>
<ListBoxItem Background="LightBlue" Foreground="Purple" Content="Orange Juice"
FontFamily="Verdana" FontSize="12" FontWeight="Bold"></ListBoxItem>
<ListBoxItem Background="LightGreen" Foreground="Green" Content="Milk" FontFamily="Georgia" FontSize="14"
FontWeight="Bold"></ListBoxItem>
<ListBoxItem Background="LightBlue" Foreground="Blue" Content="IcedTea"
FontFamily="Verdana" FontSize="12" FontWeight="Bold"></ListBoxItem>
<ListBoxItem Background="LightSlateGray" Foreground="Orange" Content="Mango Shake"
FontFamily="Georgia" FontSize="14" FontWeight="Bold"></ListBoxItem>
运行后的界面如图Figure 4:
Figure 4
Displaying Images in a ListBox
在ListBoxItem 中放置图片和文本,让图片和文本在一条线上。因为ListBoxItem中只能添加一个文本,为了添加多个文本,
需要借助容器StackPanel 控件。下面的代码段,ListBoxItem中增加了一个图片和文字。
<ListBoxItem Background="LightCoral" Foreground="Red"
FontFamily="Verdana" FontSize="12" FontWeight="Bold">
<StackPanel Orientation="Horizontal">
<Image Source="coffie.jpg" Height="30"></Image>
<TextBlock Text="Coffie"></TextBlock>
</StackPanel>
</ListBoxItem>
运行后的效果如图Figure 5:
Figure 5
ListBox with CheckBoxes
在ListBoxItem中添加复选框。复选框中添加图片和文本。XAML代码如下:
<ListBoxItem Background="LightCoral" Foreground="Red"
FontFamily="Verdana" FontSize="12" FontWeight="Bold">
<CheckBox Name="CoffieCheckBox">
<StackPanel Orientation="Horizontal">
<Image Source="coffie.jpg" Height="30"></Image>
<TextBlock Text="Coffie"></TextBlock>
</StackPanel>
</CheckBox>
</ListBoxItem>
我改变ListBoxItems 中的代码向ListBoxItems 中添加CheckBox控件。设置CheckBox的Name属性,当点击图片或者
文本时都可以选中CheckBox控件。
<ListBoxItem Background="LightCoral" Foreground="Red"
FontFamily="Verdana" FontSize="12" FontWeight="Bold">
<CheckBox Name="CoffieCheckBox">
<StackPanel Orientation="Horizontal">
<Image Source="coffie.jpg" Height="30"></Image>
<TextBlock Text="Coffie"></TextBlock>
</StackPanel>
</CheckBox>
</ListBoxItem>
<ListBoxItem Background="LightGray" Foreground="Black"
FontFamily="Georgia" FontSize="14" FontWeight="Bold">
<CheckBox Name="TeaCheckBox">
<StackPanel Orientation="Horizontal">
<Image Source="tea.jpg" Height="30"></Image>
<TextBlock Text="Tea"></TextBlock>
</StackPanel>
</CheckBox>
</ListBoxItem>
<ListBoxItem Background="LightBlue" Foreground="Purple"
FontFamily="Verdana" FontSize="12" FontWeight="Bold">
<CheckBox Name="OrangeJuiceCheckBox">
<StackPanel Orientation="Horizontal">
<Image Source="OrangeJuice.jpg" Height="40"></Image>
<TextBlock Text="OrangeJuice"></TextBlock>
</StackPanel>
</CheckBox>
</ListBoxItem>
<ListBoxItem Background="LightGreen" Foreground="Green"
FontFamily="Georgia" FontSize="14" FontWeight="Bold">
<CheckBox Name="MilkCheckBox">
<StackPanel Orientation="Horizontal">
<Image Source="Milk.jpg" Height="30"></Image>
<TextBlock Text="Milk"></TextBlock>
</StackPanel>
</CheckBox>
</ListBoxItem>
<ListBoxItem Background="LightBlue" Foreground="Blue"
FontFamily="Verdana" FontSize="12" FontWeight="Bold">
<CheckBox Name="IcedTeaCheckBox">
<StackPanel Orientation="Horizontal">
<Image Source="IcedTea.jpg" Height="30"></Image>
<TextBlock Text="Iced Tea"></TextBlock>
</StackPanel>
</CheckBox>
</ListBoxItem>
<ListBoxItem Background="LightSlateGray" Foreground="Orange"
FontFamily="Georgia" FontSize="14" FontWeight="Bold">
<CheckBox Name="MangoShakeCheckBox">
<StackPanel Orientation="Horizontal">
<Image Source="MangoShake.jpg" Height="30"></Image>
<TextBlock Text="Mango Shake"></TextBlock>
</StackPanel>
</CheckBox>
</ListBoxItem>
运行后的结果如图Figure 6:
Figure 6
Data Binding
下面介绍ListBox跟对象,数据库,XML文件以及其他控件的绑定。
Data Binding with Objects
ListBox 中的ItemsSource属性绑定到ArrayList集合上。
// Bind ArrayList with the ListBox
LeftListBox.ItemsSource = LoadListBoxData();
private ArrayList LoadListBoxData()
{
ArrayList itemsList = new ArrayList();
itemsList.Add("Coffie");
itemsList.Add("Tea");
itemsList.Add("Orange Juice");
itemsList.Add("Milk");
itemsList.Add("Mango Shake");
itemsList.Add("Iced Tea");
itemsList.Add("Soda");
itemsList.Add("Water");
return itemsList;
}
例子:从一个列表框的数据传输到另一个列表框中。点击“Add按钮”让左边的ListBox中的选中的数据添加到右边ListBox中。
点击“Remove按钮”让右边选中的数据添加到左边的ListBox中。运行后的界面如图Figure 7:
Figure 7
XAML 代码如下:
<ListBox Margin="11,13,355,11" Name="LeftListBox" />
<ListBox Margin="0,13,21,11" Name="RightListBox" HorizontalAlignment="Right"
Width="216" />
<Button Name="AddButton" Height="23" Margin="248,78,261,0" VerticalAlignment="Top"
Click="AddButton_Click">Add >></Button>
<Button Name="RemoveButton" Margin="248,121,261,117"Click="RemoveButton_Click"><< Remove</Button>
窗体加载事件中的代码:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Get data from somewhere and fill in my local ArrayList
myDataList = LoadListBoxData();
// Bind ArrayList with the ListBox
LeftListBox.ItemsSource = myDataList;
}
/// <summary>
/// Generate data. This method can bring data from a database or XML file
/// or from a Web service or generate data dynamically
/// </summary>
/// <returns></returns>
private ArrayList LoadListBoxData()
{
ArrayList itemsList = new ArrayList();
itemsList.Add("Coffie");
itemsList.Add("Tea");
itemsList.Add("Orange Juice");
itemsList.Add("Milk");
itemsList.Add("Mango Shake");
itemsList.Add("Iced Tea");
itemsList.Add("Soda");
itemsList.Add("Water");
return itemsList;
}
Add按钮事件中的代码如下:
private void AddButton_Click(object sender, RoutedEventArgs e)
{
// Find the right item and it's value and index
currentItemText = LeftListBox.SelectedValue.ToString();
currentItemIndex = LeftListBox.SelectedIndex;
RightListBox.Items.Add(currentItemText);
if (myDataList != null)
{
myDataList.RemoveAt(currentItemIndex);
}
// Refresh data binding
ApplyDataBinding();
}
/// <summary>
/// Refreshes data binding
/// </summary>
private void ApplyDataBinding()
{
LeftListBox.ItemsSource = null;
// Bind ArrayList with the ListBox
LeftListBox.ItemsSource = myDataList;
}
Remove按钮事件中的代码如下:
private void RemoveButton_Click(object sender, RoutedEventArgs e)
{
// Find the right item and it's value and index
currentItemText = RightListBox.SelectedValue.ToString();
currentItemIndex = RightListBox.SelectedIndex;
// Add RightListBox item to the ArrayList
myDataList.Add(currentItemText);
RightListBox.Items.RemoveAt(RightListBox.Items.IndexOf
(RightListBox.SelectedItem));
// Refresh data binding
ApplyDataBinding();
}
Data Binding with a Database
ListBox跟SQL Server数据库中数据的绑定。先看SQL Server数据库中的表。如图Figure 9:
Figure 9
在WPF中我们将读取数据库中的ContactName, Address, City, and Country字段。最终的ListBox显示如图Figure 10:
Figure 10
现在来看XAML文件,这个例子我们要用到资源,在其中创建DataTemplate 模板叫做listBoxTemplate。模板里面有两个DockPanel控件。
第一个中绑定的是名称字段,第二个中绑定的是地址字段。资源中的代码如下:
<Window.Resources>
<DataTemplate x:Key="listBoxTemplate">
<StackPanel Margin="3">
<DockPanel >
<TextBlock FontWeight="Bold" Text="Name:"
DockPanel.Dock="Left"
Margin="5,0,10,0"/>
<TextBlock Text=" " />
<TextBlock Text="{Binding ContactName}" Foreground="Green"FontWeight="Bold" />
</DockPanel>
<DockPanel >
<TextBlock FontWeight="Bold" Text="Address:" Foreground="DarkOrange"
DockPanel.Dock="Left"
Margin="5,0,5,0"/>
<TextBlock Text="{Binding Address}" />
<TextBlock Text=", " />
<TextBlock Text="{Binding City}" />
<TextBlock Text=", " />
<TextBlock Text="{Binding Country}" />
</DockPanel>
</StackPanel>
</DataTemplate>
</Window.Resources>
现在让我们添加ListBox 控件并设置它的绑定源和绑定模板。
<ListBox Margin="17,8,15,26" Name="listBox1" ItemsSource="{Binding Tables[0]}"
ItemTemplate="{StaticResource listBoxTemplate}" />
再就是连接数据库,获得数据,已经绑定ListBox控件的后台代码。
private void Window_Loaded(object sender, RoutedEventArgs e)
{
BindData();
}
private void BindData()
{
DataSet dtSet = new DataSet();
using (connection = new SqlConnection(connectionString))
{
command = new SqlCommand(sql, connection);
SqlDataAdapter adapter = new SqlDataAdapter();
connection.Open();
adapter.SelectCommand = command;
adapter.Fill(dtSet, "Customers");
listBox1.DataContext = dtSet;
}
}
Data Binding with XML
现在让我们来看看怎么绑定XML文件中的数据集到ListBox控件上。XML文件中的代码如下:
<XmlDataProvider x:Key="BooksData" XPath="Inventory/Books">
<x:XData>
<Inventory xmlns="">
<Books>
<Book Category="Programming" >
<Title>A Programmer's Guide to ADO.NET</Title>
<Summary>Learn how to write database applications usingADO.net and C#.
</Summary>
<Author>Mahesh Chand</Author>
<Publisher>APress</Publisher>
</Book>
<Book Category="Programming" >
<Title>Graphics Programming with GDI+</Title>
<Summary>Learn how to write graphics applications using GDI+and C#.
</Summary>
<Author>Mahesh Chand</Author>
<Publisher>Addison Wesley</Publisher>
</Book>
<Book Category="Programming" >
<Title>Visual C#</Title>
<Summary>Learn how to write C# applications.
</Summary>
<Author>Mike Gold</Author>
<Publisher>APress</Publisher>
</Book>
<Book Category="Programming" >
<Title>Introducing Microsoft .NET</Title>
<Summary>Programming .NET
</Summary>
<Author>Mathew Cochran</Author>
<Publisher>APress</Publisher>
</Book>
<Book Category="Database" >
<Title>DBA Express</Title>
<Summary>DBA's Handbook
</Summary>
<Author>Mahesh Chand</Author>
<Publisher>Microsoft</Publisher>
</Book>
</Books>
</Inventory>
</x:XData>
</XmlDataProvider>
接下来就是绑定XmlDataProvider。我们设置ItemsSource绑定到XmlDataProvider的x:Key值上。用XPath绑定XML中的数据。
模板里面绑定属性。XAML中的代码,我们可以看到非常的简洁。
<ListBox Width="400" Height="300" Background="LightGray">
<ListBox.ItemsSource>
<Binding Source="{StaticResource BooksData}"
XPath="*[@Category='Programming'] "/>
</ListBox.ItemsSource>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Title: " FontWeight="Bold"/>
<TextBlock Foreground="Green" >
<TextBlock.Text>
<Binding XPath="Title"/>
</TextBlock.Text>
</TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
运行后的界面如图Figure 11:
Figure 11
Data Binding with Controls
最后一个例子看看ListBox怎么样和别的控件绑定。我们先来看看运行后的界面Figure 12:
Figure 12
选择ListBox中的一个颜色,把选中的值赋给文本框,并且赋给Canvas控件,让它改变颜色。以下就是XAML中的代码:
<StackPanel Orientation="Vertical">
<TextBlock Margin="10,10,10,10" FontWeight="Bold">
Pick a color from below list
</TextBlock>
<ListBox Name="mcListBox" Height="100" Width="100"Margin="10,10,0,0" HorizontalAlignment="Left" >
<ListBoxItem>Orange</ListBoxItem>
<ListBoxItem>Green</ListBoxItem>
<ListBoxItem>Blue</ListBoxItem>
<ListBoxItem>Gray</ListBoxItem>
<ListBoxItem>LightGray</ListBoxItem>
<ListBoxItem>Red</ListBoxItem>
</ListBox>
<TextBox Height="23" Name="textBox1" Width="120" Margin="10,10,0,0"
HorizontalAlignment="Left" >
<TextBox.Text>
<Binding ElementName="mcListBox" Path="SelectedItem.Content"/>
</TextBox.Text>
</TextBox>
<Canvas Margin="10,10,0,0" Height="200" Width="200" HorizontalAlignment="Left">
<Canvas.Background>
<Binding ElementName="mcListBox" Path="SelectedItem.Content"/>
</Canvas.Background>
</Canvas>
</StackPanel>