WPF中的ListBox详解

发布于:2025-07-16 ⋅ 阅读:(20) ⋅ 点赞:(0)

简介

【ListBox】是列表控件,其内部可包含多个【ListBoxItem】,用户可以从列表中选择一个或多个项,若Item个数超过指定高度,则右侧会自动出现滚动条,非常便捷。尽管逻辑上来说,ListBox里面就应该装载ListBoxiItem,但实际上也可以装载其他控件,示例如下

在这里插入图片描述

其WPF代码为

<ListBox x:Name="lbDev" Height="100">
    <ListBoxItem Content="ListBoxItem A"/>
    <ListBoxItem Content="ListBoxItem B"/>
    <Button Content="Button"/>
    <TextBox Text="TextBox"/>
    <ListBoxItem Content="ListBoxItem C"/>
</ListBox>

ListBoxItem

【ListBoxItem】作为ListBox默认的子控件,其功能相对比较完备,在外观属性上,支持颜色、字体以及背景图片等美化;在动作上,支持双击。此外,还可以用其他控件来填充其Content,从而实现更复杂的功能。

下图分别对A, B, C三个Item进行了定制:为A设计了前景色和文字颜色;为B中添加了图片;将C封装成了单选框。

在这里插入图片描述

其WPF代码如下

<ListBox x:Name="lbDev" Height="100">
    <ListBoxItem Content="ListBoxItem A" Background="LightBlue" Foreground="Purple"/>
    <ListBoxItem>
        <StackPanel Orientation="Horizontal">
            <Image Source="E:\work\code\doc\imgs\PI_H811.jpg" Height="30"/>
            <TextBlock Text="ListBoxItem B"></TextBlock>
        </StackPanel>
    </ListBoxItem>
    <ListBoxItem>
        <CheckBox Content="ListBoxItem C"/>
    </ListBoxItem>
</ListBox>

其中,B和C都其Content进行了定制,且B中采用了StackPanel布局,理论上讲,甚至可以插入一整个页面。

由于单击操作被用于选中项目,故ListBoxItem中,用【Selected】来绑定单击事件,而双击操作【MouseDoubleClick】则不受影响,其绑定方式和普通的按钮没什么区别,故不再赘述了。

选中项目

之所以采用ListBox,主要原因是其子控件有一定的相似性,所以实际编程中,往往在ListBox这个层次来协调其子控件的选中等操作,示例如下

在这里插入图片描述

WPF代码为

<ListBox x:Name="lbDev" Height="60" SelectionChanged="lbDev_SelectionChanged" MouseDoubleClick="lbDev_MouseDoubleClick" >
    <ListBoxItem Content="ListBoxItem A"/>
    <ListBoxItem Content="ListBoxItem B"/>
    <ListBoxItem Content="ListBoxItem C"/>
</ListBox>
<TextBox x:Name="tbInfo" Height="50"/>

C#代码为

private void lbDev_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    tbInfo.Text = $"选中第{lbDev.SelectedIndex}个Item";
}


private void lbDev_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    tbInfo.Text = $"双击第{lbDev.SelectedIndex}个Item";
}    

动态列表

ListBox支持动态添加和删除Item,如下图所示
在这里插入图片描述

其wpf代码为

<ListBox x:Name="lbDev" Height="60">
</ListBox>
<UniformGrid Columns="3">
    <TextBox x:Name="tbName"/>
    <Button Content="添加Item" Click="btnAddItem_Click"/>
    <Button Content="删除Item" Click="btnRmItem_Click"/>
</UniformGrid>

C#代码为

private void btnAddItem_Click(object sender, RoutedEventArgs e)
{
    lbDev.Items.Add(new ListBoxItem() { Content = tbName.Text });
}

private void btnRmItem_Click(object sender, RoutedEventArgs e)
{
    lbDev.Items.RemoveAt(lbDev.SelectedIndex);
}

其中【RemoveAt】可以删除指定位置的Item,也可以用【Remove】删除指定的Item。此外,【Clear】可以删除所有Item。


网站公告

今日签到

点亮在社区的每一天
去签到