先从最容易的开始演示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 &gt;&gt;</Button>
<Button Name="RemoveButton" Margin="248,121,261,117"Click="RemoveButton_Click">&lt;&lt; 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的创建和多种绑定用法的更多相关文章

  1. WPF中ListBox的项ListBoxItem被选中的时候Background变化

    使用WPF 中ListBox,点击ListBoxItem的时候,自定义它的背景色,曾经在网上找了一些方法, 不是很理想,后来在StackOverflow上找到了,贴出代码和效果图: 效果图:

  2. WPF中ListBox滚动时的缓动效果

    原文:WPF中ListBox滚动时的缓动效果 上周工作中遇到的问题: 常规的ListBox在滚动时总是一格格的移动,感觉上很生硬. 所以想要实现类似Flash中的那种缓动的效果,使ListBox滚动时 ...

  3. 整理:WPF中应用附加事件制作可以绑定命令的其他事件

    原文:整理:WPF中应用附加事件制作可以绑定命令的其他事件 目的:应用附加事件的方式定义可以绑定的事件,如MouseLeftButton.MouseDouble等等 一.定义属于Control的附加事 ...

  4. WPF中ListBox /ListView如何改变选中条背景颜色

    适用ListBox /ListView WPF中LISTVIEW如何改变选中条背景颜色 https://www.cnblogs.com/sjqq/p/7828119.html

  5. WPF中ListBox的绑定

    WPF中列表式控件派生自ItemsControl类,继承了ItemsSource属性.ItemsSource属性可以接收一个IEnumerable接口派生类的实例作为自己的值(所有可被迭代遍历的集合都 ...

  6. 在WPF中一种较好的绑定Enums数据方法

    引言 在你使用wpf应用程序开发的时候,是否需要进行数据绑定到Enum数据呢?在这篇文章中,我将向你展示在WPF中处理Enum数据绑定的方法. 假设存在一个这样的Enum数据的定义,具体内容如下文代码 ...

  7. WPF中ListBox控件在选择模式(SelectionMode)为Single时仍然出现多个Item被选中的问题

    最近在学习WPF过程中使用到了ListBox控件,在使用时遇到下面的奇怪问题: 代码如下: listBox.Items.Add("绘图"); listBox.Items.Add(& ...

  8. WPF中ListBox ListView数据翻页浏览笔记(强调:是数据翻页,非翻页动画)

    ListBox和ListView在应用中,常常有需求关于每页显示固定数量的数据,然后通过Timer自动或者手动翻页操作,本文介绍到的就是该动作的实现. 一.重点 对于ListBox和ListView来 ...

  9. WPF中ListBox的样式设置

    设置之后的效果为

随机推荐

  1. 10. CTF综合靶机渗透(三)

    靶机说明 斗牛犬工业公司最近将其网站污损,并由恶意德国牧羊犬黑客团队拥有.这是否意味着有更多的漏洞可以利用?你为什么不知道?:) 这是标准的Boot-to-Root.你唯一的目标是进入根目录并看到祝贺 ...

  2. From COM to COM 侯捷 1998.06.12

    摘要: 本文簡介 C++ Object Model 和 Component Object Model 的基本概念,並引介四本書籍: 1. Inside The C++ Object Model 2. ...

  3. HTTP协议格式及基础

    HTTP请求数据: HTTP请求信息由3部分组成: ① 请求方法 URI 协议/版本 ② 请求头(Request Header) ③     请求正文 HTTP 请求 数据 例子举例: GET/sam ...

  4. [WIP]laravel 构成的概念

    创建: 2019/06/21 生命周期  概论    检索service provider               service container                     se ...

  5. c++第六次实验

    part 1 验证性实验 合并两个文件.虽说验证,但后两个实验均受该代码指导启发. part 2  文末添加数据 1.代码 #include<fstream> #include<io ...

  6. java知识点积累(二)

    4.条件运算符(三元运算符): String type = score<60?"不及格":"及格"; int i = (string=="hel ...

  7. UML——前两章

    前言 软件开发过程中,在生命周期中,我们大都知道要写文档,但是针对这种团队集体完成的事情,如果中间出现了人员流动问题,这时侯有文档仅仅是不够的.为了让大多数开发人员和用户能直观的了解软件开发的进度和流 ...

  8. postgres_fdw

    create extension postgres_fdw; --创建扩展 create server db0 foreign data wrapper postgres_fdw OPTIONS (h ...

  9. C 语言实例 - 计算一个数的 n 次方

    C 语言实例 - 计算一个数的 n 次方 计算一个数的 n 次方,例如: ,其中 为基数, 为指数. 实例 - 使用 while #include <stdio.h> int main() ...

  10. Luogu P4161 [SCOI2009]游戏 数论+DP

    ywy神犇太巨辣!!一下就明白了!! 题意:求$lcm(a_1,a_2,...,a_k)$的种类,其中$\Sigma\space a_i <=n$,$a_i$相当于环长 此处的$DP$,相当于是 ...