Set a background image to Listbox item

↘锁芯ラ 提交于 2020-01-23 17:02:13

问题


I'm able to set an image to Listbox using the background property. But how do I set a desirable image as a background to items of the listbox?

Thanks.


回答1:


You'll have to redefine the ItemTemplate property of the ListBox. If you're not confident with XAML, you should try using Expression Blend.

Here is an example of how you're XAML could look like. I created a new application using the Pivot Template application.

        <ListBox x:Name="FirstListBox" Margin="0,0,-12,0" ItemsSource="{Binding Items}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                  <StackPanel Margin="0,0,0,17" Width="432" Height="78">
                    <StackPanel.Background>
                        <ImageBrush Stretch="Fill" ImageSource="/Koala.jpg"/>
                    </StackPanel.Background>
                      <TextBlock Text="{Binding LineOne}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                      <TextBlock Text="{Binding LineTwo}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
                  </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

So the default ItemTemplate uses a StackPanel as main container. What you want to do here, is to set the image as the background of that StackPanel. That's what the following lines stands for:

                <StackPanel.Background>
                    <ImageBrush Stretch="Fill" ImageSource="/Koala.jpg"/>
                </StackPanel.Background>

With the above code, you set an ImageBrush as the Background property of the StackPanel.

With that code, each ListBoxItem will display a koala.




回答2:


Wrapping the listbox item using border and setting the background might help.Follow this sample

  <Border Width="380" Height="60" Margin="0,0,0,10" >
       <Border.Background>
          <ImageBrush ImageSource="Images/menu_bg.png" />
       </Border.Background>
       <TextBlock  Foreground="Black" FontSize="22" Text="{Binding}" HorizontalAlignment="Center" VerticalAlignment="Center"  />
   </Border>


来源:https://stackoverflow.com/questions/10497056/set-a-background-image-to-listbox-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!