开发工具与关键技术: 列表控件
作者:邓崇富
撰写时间:2019 年7 月 16 日
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1、ListBox控件:
ListBox类代表了一种最长用的Windows设计,允许用户从长度可变的列表中选择一项:为向ListBox控件中添加项,可在ListBox元素中嵌套ListBoxItem元素。例如,下面是一个包含颜色列表的ListBox:
<Grid>
<ListBox>
<ListBoxItem>Green</ListBoxItem>
<ListBoxItem>Blue</ListBoxItem>
<ListBoxItem>Yellow</ListBoxItem>
<ListBoxItem>Red</ListBoxItem>
</ListBox>
</Grid>
ListBox控件是一个非常灵活的控件。它不仅可以包含ListBoxItem对象,也可以驻留其它任意元素。这是因为ListBoxItem类继承自ContentControl类,从而ListBoxItem能够包含一段嵌套的内容。如果该内容继承自UIElememt类,它将在ListBox控件中呈现出来。如果是其他类型的对象,ListBoxItem对象会调用ToString()方法显示最终得文本。
例如,如果决定创建一个包含图像得列表,可使用如下标记:
<Grid>
<ListBox>
<Image Source="G:\项目\WPF课件练习\WPF课件练习\images\325360.jpg"/>
</ListBox>
<ListBoxItem>
<Image Source="G:\项目\WPF课件练习\WPF课件练习\images\325476.jpg"/>
</ListBoxItem>
</Grid>
实际上ListBox控件足够智能,它能隐式地创建所需得ListBoxItem对象。这意味着可以直接在ListBox元素中放置对象。下面是一个更复杂得示例,该例使用嵌套的StackPanel对象组合文本和图像内容:
<Grid>
<ListBox>
<StackPanel Orientation="Horizontal">
<Image Source="G:\项目\WPF课件练习\WPF课件练习\images\325360.jpg" Width="60" Height="60"/>
<Label VerticalContentAlignment="Center" Content="图片1"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Image Source="G:\项目\WPF课件练习\WPF课件练习\images\325512.jpg" Width="60" Height="60"/>
<Label VerticalContentAlignment="Center" Content="图片2"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Image Source="G:\项目\WPF课件练习\WPF课件练习\images\325272.jpg" Width="60" Height="60"/>
<Label VerticalContentAlignment="Center" Content="图片3"/>
</StackPanel>
</ListBox>
</Grid>
在该例中,StackPanel面板变被ListBoxItem封装的项。该标记创建的富列表如下图:
注意:在前面的设计中,有一个缺点是当前里列表项被选中时文本颜色不能随之改变。
2、CheckBox:
利用在列表框中能嵌套任意元素的能力,可以创建出各种基于列表的控件,而不必使用其他类,例如,Windows窗体的工具箱中有CheckedListBox类,该类显示在每个项的旁边都具有副选框的列表。在WPF中不需要这以特殊类,因为完全可使用标准的ListBox控件快速构建相同的效果:
<Grid>
<ListBox Name="list" SelectionChanged="List_SelectionChanged" CheckBox.Click="List_Click">
<CheckBox Margin="3" Content="Option1"/>
<CheckBox Margin="3" Content="Option2"/>
</ListBox>
</Grid>
当在列表内部使用不同元素时需要注意一点,当读取SelectedItem值时(以及SelectedItems和Items集合),看不到ListBoxItem对象,反而将看到放入到列表中的对象。在CheckedListBox示例中,这意味着SelectedItem提供了CheckBox对象。
例如,下面是一些响应SelectionChanged事件触发的代码.这段代码获取当前选中的CheckBox对象并显示该项是否被选中:
private void List_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (list.SelectedItem == null) return;
txtSelection.Text = string.Format(
"You chose item at position {0},\r\nChecked state is {1}.", list.SelectedIndex, ((CheckBox)list.SelectedItem).IsChecked);
}
在下面的代码段中,类似的代码遍历选项集合以确定哪一项被选中了(对复选框的多项选择列表,可以编写类似的代码来遍历选中的集合):
private void cmd_ExamineAllItems(object sender, RoutedEventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach (CheckBox item in list.Items)
{
if (item.IsChecked == true)
{
sb.Append(intem.Content);
sb.Append("is checked.");
sb.Append("\r\n");
}
}
txtSelection.Text = sb.ToString();
}