列表控件 ListBox、ComboBox

列表控件能夠看成容器,內部能夠有RadioButton、CheckBox、StackPanel等。即Items類型多樣。app

ListBox,多個Item可被選中;ComboBox,只能有一個Item被選中。ui

    <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();
        }
相關文章
相關標籤/搜索