博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
WPF中ListBox的创建和多种绑定用法
阅读量:7102 次
发布时间:2019-06-28

本文共 9225 字,大约阅读时间需要 30 分钟。

本篇博文为翻译(),本篇博文主要介绍ListBox控件的创建和用法。<ListBox></ListBox>

先从最容易的开始演示ListBox控件的创建。

Adding ListBox Items

下面的代码是向ListBox控件中添加多项ListBoxItem集合。XAML代码如下:

  

运行后的界面如图 Figure 1:

                Figure 1

Adding ListBox Items Dynamically

动态添加ListBox集合项。用一个文本框,一个按钮。当点击添加按钮向ListBox控件中添加用法输入文本框的值。XAML代码如下:

  

运行后的界面如图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的属性:

 

运行后的界面如图Figure 4:

                Figure 4

Displaying Images in a ListBox

在ListBoxItem 中放置图片和文本,让图片和文本在一条线上。因为ListBoxItem中只能添加一个文本,为了添加多个文本,

需要借助容器StackPanel 控件。下面的代码段,ListBoxItem中增加了一个图片和文字。

 

运行后的效果如图Figure 5:

                Figure 5

ListBox with CheckBoxes

在ListBoxItem中添加复选框。复选框中添加图片和文本。XAML代码如下:

 

我改变ListBoxItems 中的代码向ListBoxItems 中添加CheckBox控件。设置CheckBox的Name属性,当点击图片或者

文本时都可以选中CheckBox控件。

 

运行后的结果如图Figure 6:

              Figure 6

Data Binding
下面介绍ListBox跟对象,数据库,XML文件以及其他控件的绑定。
Data Binding with Objects
ListBox 中的ItemsSource属性绑定到ArrayList集合上。

// Bind ArrayList with the ListBoxLeftListBox.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 代码如下:

 

窗体加载事件中的代码:

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;           } /// /// Generate data. This method can bring data from a database or XML file/// or from a Web service or generate data dynamically/// /// 
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();} /// /// Refreshes data binding/// 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控件。

第一个中绑定的是名称字段,第二个中绑定的是地址字段。资源中的代码如下:

 

现在让我们添加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文件中的代码如下:

A Programmer's Guide to ADO.NET
Learn how to write database applications usingADO.NET and C#.
Mahesh Chand
APress
Graphics Programming with GDI+
Learn how to write graphics applications using GDI+and C#.
Mahesh Chand
Addison Wesley
Visual C#
Learn how to write C# applications.
Mike Gold
APress
Introducing Microsoft .NET
Programming .NET
Mathew Cochran
APress
DBA Express
DBA's Handbook
Mahesh Chand
Microsoft

 

接下来就是绑定XmlDataProvider。我们设置ItemsSource绑定到XmlDataProvider的x:Key值上。用XPath绑定XML中的数据。

模板里面绑定属性。XAML中的代码,我们可以看到非常的简洁。

 

运行后的界面如图Figure 11:

               Figure 11

Data Binding with Controls
最后一个例子看看ListBox怎么样和别的控件绑定。我们先来看看运行后的界面Figure 12:

            Figure 12

选择ListBox中的一个颜色,把选中的值赋给文本框,并且赋给Canvas控件,让它改变颜色。以下就是XAML中的代码:

Pick a color from below list
Orange
Green
Blue
Gray
LightGray
Red

 

转载于:https://www.cnblogs.com/Health/archive/2012/02/17/2355924.html

你可能感兴趣的文章
list,tuple,set,dict基础
查看>>
PIC中的#pragma idata 和#pragma udata
查看>>
使用FileAudit在Windows服务器上实现最优文件访问监控
查看>>
mysql 远程连接数据库的二种方法
查看>>
一步一步学android OpenGL ES2.0编程(4)
查看>>
corosync 源代码分析1
查看>>
寻找Cydia里面软件安装包deb文件的真实下载地址
查看>>
如何收缩日志文件
查看>>
解决Excel打开UTF-8编码的CSV文件乱码的问题
查看>>
Powershell invoke-command vs -computerName 效率比较
查看>>
送给那些有代码基础但仍旧不会学自动化测试的朋友们
查看>>
做公关必用的四大法宝
查看>>
Microsoft Hyper-V Server 2012开启虚拟化-虚拟机管理
查看>>
Linux下Oracle设置环境变量
查看>>
VBScript的字符串方法
查看>>
C和汇编调用一例
查看>>
分享:TokuDB v7 发布,并宣布全面开源
查看>>
系统工具技术选择 – 我们为什么不选择Puppet?
查看>>
ZOJ-2788 Panic Room 最小割
查看>>
hdu 1175:连连看(dfs 深度优先搜索)
查看>>