WPF ListBoxItem模板

在一次课程设计中,制作聊天软件的好友列表功能,本文介绍如何创建一个带有图标的WPF ListBoxItem样式模板。通过设置APP.xaml中的样式模板,无论是静态还是动态添加的ListBoxItem都将应用此效果,提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在做一个课程设计,主要做一个聊天软件,其中要做一个好友列表,虽然做的不是很精美,但是学习还是有用的。

这个模板主要是实现一个带有图标的ListBoxItem的效果

如下图:


这个ListBoxItem是写在APP.XML中的以个样式模板,每次添加的ListBoxItem都会应用到,动态的也会应用这个样式。模板在msdn里面有


下面是代码

<Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="SnapsToDevicePixels" Value="true"/>
            <Setter Property="OverridesDefaultStyle" Value="true"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <Border 
                       Name="Border"
                       Padding="2"
                        SnapsToDevicePixels="true">

                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="30"/>
                                    <ColumnDefinition/>
                                </Grid.ColumnDefinitions>
                                <Image Width="30" Height="30" Source="Img/header.ico" Grid.Column="0"/>
                                <ContentPresenter Grid.Column="1" VerticalAlignment="Center" ></ContentPresenter>
                            </Grid>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsSelected" Value="true">
                                <Setter TargetName="Border" Property="Background"
                    Value="Blue"/>
                            </Trigger>
                            <Trigger Property="IsEnabled" Value="false">
                                <Setter Property="Foreground"
                    Value="White"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

引用代码

<ListBox>
                        <ListBoxItem>我去你妹的</ListBoxItem>
                        <ListBoxItem>我去你妹的</ListBoxItem>
                        <ListBoxItem>我去你妹的</ListBoxItem>
                        <ListBoxItem>我去你妹的</ListBoxItem>
                    </ListBox>

希望这段代码对正在学习WPF的同学有帮助




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值