WPF-ListBox

这里还是使用一个demo来展示ListBox的使用,这里是用LIstBox嵌套CheckBox,使用ListBox的SelectionChanged事件来实时告诉使用者选中了那个复选框,是true还是false。并最后有统计按钮,统计总共选了那些复选框。

<Window x:Class="list.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <ListBox Name="lst" Margin="5" SelectionChanged="ListBox_SelectionChanged" >
            <CheckBox Margin="3">Option1</CheckBox>
            <CheckBox Margin="3">Option2</CheckBox>
            <CheckBox Margin="3">Option3</CheckBox>
        </ListBox>
        <StackPanel  Grid.Row="1" >
            <TextBlock>Current selection</TextBlock>
            <TextBlock TextWrapping="Wrap" Name="text"></TextBlock>
            <Button Name="exa" Click="exa_Click">Examine all items</Button>
        </StackPanel>
    </Grid>
</Window>
namespace list
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lst.SelectedItem == null) return;
            text.Text = "You chose item at position" + lst.SelectedIndex +"\r\n" +((CheckBox)lst.SelectedItem).IsChecked;
        }

        private void exa_Click(object sender, RoutedEventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            foreach (CheckBox cb in lst.Items) {
                if (cb.IsChecked == true) {
                    sb.Append(cb.Content);
                    sb.Append("is checked");
                    sb.Append("\r\n");
                }
                text.Text = sb.ToString();
            }
        }
    }
}

效果图
选中CheckBox
这里写图片描述
点击统计按钮后
这里写图片描述

猜你喜欢

转载自blog.csdn.net/Maybe_ch/article/details/80610679