列表控件 ListBox、ComboBox
列表控件可以当作容器,内部可以有RadioButton、CheckBox、StackPanel等。即Items类型多样。
ListBox,多个Item可被选中;ComboBox,只能有一个Item被选中。
<Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <ListBox x:Name="listBox" Margin="5" SelectionChanged="listBox_SelectionChanged" > <CheckBox x:Name="checkBox" Content="CheckBox"/> <CheckBox x:Name="checkBox1" Content="CheckBox1"/> <CheckBox x:Name="checkBox2" Content="CheckBox2"/> </ListBox> <StackPanel Grid.Row="1" Margin="5"> <TextBlock Text="选中结果"/> <TextBlock x:Name="textBlock" TextWrapping="Wrap"/> <Button x:Name="button" Content="统计" HorizontalAlignment="Center" Click="button_Click"/> </StackPanel> </Grid>
private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (listBox.SelectedItem==null) { return; } textBlock.Text = "选中的是:" +((CheckBox)listBox.SelectedItem).Content+"\n状态:" + ((CheckBox)listBox.SelectedItem).IsChecked; } private void button_Click(object sender, RoutedEventArgs e) { StringBuilder sb = new StringBuilder(); foreach (CheckBox item in listBox.Items) { if (item.IsChecked==true) { sb.Append(item.Content+"被选中\n"); } } textBlock.Text = sb.ToString(); }