转:WPF中ListBox的创建和多种绑定用法
先从最容易的开始演示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>
转:WPF中ListBox的创建和多种绑定用法的更多相关文章
- WPF中ListBox的项ListBoxItem被选中的时候Background变化
使用WPF 中ListBox,点击ListBoxItem的时候,自定义它的背景色,曾经在网上找了一些方法, 不是很理想,后来在StackOverflow上找到了,贴出代码和效果图: 效果图:
- WPF中ListBox滚动时的缓动效果
原文:WPF中ListBox滚动时的缓动效果 上周工作中遇到的问题: 常规的ListBox在滚动时总是一格格的移动,感觉上很生硬. 所以想要实现类似Flash中的那种缓动的效果,使ListBox滚动时 ...
- 整理:WPF中应用附加事件制作可以绑定命令的其他事件
原文:整理:WPF中应用附加事件制作可以绑定命令的其他事件 目的:应用附加事件的方式定义可以绑定的事件,如MouseLeftButton.MouseDouble等等 一.定义属于Control的附加事 ...
- WPF中ListBox /ListView如何改变选中条背景颜色
适用ListBox /ListView WPF中LISTVIEW如何改变选中条背景颜色 https://www.cnblogs.com/sjqq/p/7828119.html
- WPF中ListBox的绑定
WPF中列表式控件派生自ItemsControl类,继承了ItemsSource属性.ItemsSource属性可以接收一个IEnumerable接口派生类的实例作为自己的值(所有可被迭代遍历的集合都 ...
- 在WPF中一种较好的绑定Enums数据方法
引言 在你使用wpf应用程序开发的时候,是否需要进行数据绑定到Enum数据呢?在这篇文章中,我将向你展示在WPF中处理Enum数据绑定的方法. 假设存在一个这样的Enum数据的定义,具体内容如下文代码 ...
- WPF中ListBox控件在选择模式(SelectionMode)为Single时仍然出现多个Item被选中的问题
最近在学习WPF过程中使用到了ListBox控件,在使用时遇到下面的奇怪问题: 代码如下: listBox.Items.Add("绘图"); listBox.Items.Add(& ...
- WPF中ListBox ListView数据翻页浏览笔记(强调:是数据翻页,非翻页动画)
ListBox和ListView在应用中,常常有需求关于每页显示固定数量的数据,然后通过Timer自动或者手动翻页操作,本文介绍到的就是该动作的实现. 一.重点 对于ListBox和ListView来 ...
- WPF中ListBox的样式设置
设置之后的效果为
随机推荐
- C#中的new修饰符说明
new修饰符主要是用来隐藏从基类继承的成员. 这句话怎么理解呢,就是说有一个类,它有一个继承类,继承类中存在和基类中一样名称的成员(属性,方法等). 对继承类中的该成员使用new修饰符时,调用时将会隐 ...
- 连接mysql时报:message from server: "Host '192.168.76.89' is not allowed to connect to this MySQL server 处理方案
1.先用localhost方式连接到MySQL数据库,然后使用MySQL自带的数据库mysql; use mysql: 2.执行:select host from user where user = ...
- 3、jquery_动态创建元素
动态创建元素:$('<b>javier</b>') $('#Button1').append($('<b>javier</b>')) 等价于 $($( ...
- 【leetcode 105. 从前序与中序遍历序列构造二叉树】解题报告
前往 中序,后序遍历构造二叉树, 中序,前序遍历构造二叉树 TreeNode* build(vector<int>& preorder, int l1, int r1, vecto ...
- Cogs 9. 中心台站建设
9. 中心台站建设 ★★☆ 输入文件:zpj.in 输出文件:zpj.out 简单对比时间限制:1 s 内存限制:128 MB [问题描述] n个城市之间有通讯网络,从这n个城 ...
- iOS回顾笔记( 01 )-- XIB和纯代码创建应用的对比
header{font-size:1em;padding-top:1.5em;padding-bottom:1.5em} .markdown-body{overflow:hidden} .markdo ...
- Java Script 第二章.
对象: JavaScript中的所有事物都是对象:字符串,数组,数值,函数..... JavaScript中提供多个内建对象,比如说 String, Date, Array等等.对象只是带有属性和 ...
- 2、kubeadm快速部署kubernetes(v1.15.0)集群190623
一.网络规划 节点网络:192.168.100.0/24 Service网络:10.96.0.0/12 Pod网络(默认):10.244.0.0/16 二.组件分布及节点规划 master(192.1 ...
- Poj 2096 (dp求期望 入门)
/ dp求期望的题. 题意:一个软件有s个子系统,会产生n种bug. 某人一天发现一个bug,这个bug属于某种bug,发生在某个子系统中. 求找到所有的n种bug,且每个子系统都找到bug,这样所要 ...
- TOMCAT热部署 catalina.home catalina.base
catalina.home 一台机器通常只有一个, 指向Tomcat的安装目录 catalina.base 一台机器可以启动多个Context, 每个Context对应一个catalina.base ...