WPF: Adding an image to a ListBox ItemTemplate

十年热恋 提交于 2019-12-23 09:48:27

问题


I am creating a WPF app with a list box that I am binding to project names. As a decorative element, I want to place a small icon next to each item in the list, similar to the way Outlook does in its Personal Folders list. For starters, I am going to use the same image for all items in the list.

Here is the markup that I've got so far (I'll move it to a resource dictionary after it's working):

<ListBox.Resources>
    <ImageBrush x:Key="ProjectIcon" ImageSource="Images/project.png" />
</ListBox.Resources>
<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <Image Source="{StaticResource ProjectIcon}"/>
            <TextBlock Text="{Binding Path=Name}" />
        </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

I've got an error in the image resource, but I'm not sure how to fix it. Any suggestions? Thanks.


回答1:


The Source property of an Image is of type ImageSource not ImageBrush. The following should work:

<ListBox.Resources>
    <BitmapImage x:Key="ProjectIcon" UriSource="Images/project.png" />
</ListBox.Resources>
<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <Image Source="{StaticResource ProjectIcon}"/>
            <TextBlock Text="{Binding Path=Name}" />
        </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>


来源:https://stackoverflow.com/questions/2081900/wpf-adding-an-image-to-a-listbox-itemtemplate

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