本篇博文為翻譯(http://www.c-sharpcorner.com/uploadfile/mahesh/listbox-in-wpf/),本篇博文主要介紹ListBox控件的創建和用法。<ListBox></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>