【问题标题】:Adding image on top of ListBoxItem in WPF在 WPF 中的 ListBoxItem 顶部添加图像
【发布时间】:2011-12-30 12:38:36
【问题描述】:

我有一个带有一些 ListBoxItems 的 ListBox。每个 ListBoxItem 都包含一些文本和一个背景图像。当用户单击 ListBoxItem 时,我想在 ListBoxItem 顶部添加一个图像(它用一些额外的外观装饰该项目)。

我正在寻找一种将图像叠加到单击的 ListBoxItem 上的方法。这是我到目前为止的代码:

    <ListBox Margin="0,34,0,25.113" Background="{x:Null}" BorderThickness="0">
        <ListBoxItem Content="First Item" Height="71.96" Margin="0,10,0,0">
            <ListBoxItem.Background>
                <ImageBrush ImageSource="Untitled-4.png"/>
            </ListBoxItem.Background>
        </ListBoxItem>
    </ListBox>

【问题讨论】:

    标签: wpf listboxitem


    【解决方案1】:

    将您的ListBoxItem.Content 放在允许重叠控件的面板中,例如Grid,并使顶部图像的Visibililty 基于ListBoxItem.IsSelected

    <ListBox.Resources>
        <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
    </ListBox.Resources>
    
    <ListBoxItem Height="71.96" Margin="0,10,0,0">
        <ListBoxItem.Background>
            <ImageBrush ImageSource="Untitled-4.png"/>
        </ListBoxItem.Background>
        <Grid>
            <TextBlock Text="First Item" 
                       VerticalAlignment="Center" HorizontalAlignment="Center" />
    
            <Image Source="SomeImage.jpg"
                   Visibility="{Binding IsSelected, 
                       RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}, 
                       Converter={StaticResource BooleanToVisibilityConverter}}" />
        </Grid>
    </ListBoxItem>
    

    编辑

    您还可以通过覆盖 HighlightBrush 颜色并使其透明来移除 SelectedItem 的蓝色背景

    <ListBox.Resources>
        <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
    
        <Style TargetType="{x:Type ListBoxItem}">
            <Style.Resources>
                <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
                <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" />
            </Style.Resources>
        </Style>
    </ListBox.Resources>
    

    【讨论】:

    • 谢谢你,它以某种方式工作!但是,当我单击一个元素时,我会得到一个蓝色项目,我认为这是因为 select 事件。单击时是否可以删除此蓝色选择?谢谢。
    • 在第二个注释中,看起来文本与其他元素是分开的。我希望文本位于中间,但文本现在位于顶部,而图像(​​在网格中)位于其下方;图像没有覆盖网格的内容。
    • @Ali 我更新了我的答案。设置TextBlock Alignment 将其定位在网格的中心,并调整ListBoxItem 样式以更改高光画笔颜色
    猜你喜欢
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多