ListBox控件
ListBox控件继承自ContentControl类,是一个容器类的控件,向ListBox控件中包含ListBoxItem元素向容器中添加成分,也可以添加其他任意的控件。
<ListBox x:Name="listBox" Margin="5" Height="auto" VerticalAlignment="Top">
<ListBoxItem>
<Image Source="" Height="30"/>
</ListBoxItem>
<ListBoxItem>Blue</ListBoxItem>
<StackPanel Orientation="Horizontal">
<Image Source="" Height="30"/>
<Label VerticalContentAlignment="Center">
Picture
</Label>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Image Source="" Height="30"/>
<Label>
Next Picture
</Label>
</StackPanel>
</ListBox>
在ListBox中放置CheckBox默认相当于放置了一个ListBoxItem。当选择ListBox中的元素时,可触发SelectionChanged事件。
private void lst_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lst.SelectedItem == null) return;
this.txtselection.Text = "You choose item at position" + (lst.SelectedIndex + 1);
}
利用SelectedIndex
属性可以获取用户在ListBox中选择的序号。
下面这个例子利用循环的方式获取所有选中的ListBox内容。
对ListBox中的每一个CheckBox item,判断item.IsChecked是否选中,并用item.Content提取这个item的内容。
private void Button_Click(object sender, RoutedEventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach (CheckBox item in lst.Items)
{
if (item.IsChecked == true)
{
sb.Append(item.Content);
sb.Append(" is checked");
sb.Append("\r\n");
}
txtselection.Text = sb.ToString();
}
}
点击按钮就可以显示所有选中的CheckBox的content内容。
ComboBox使用与ListBox类似,只是形式变成了下拉框。对应的内含元素是ComboBoxItem。