WPF: Adding an image to a ListBox ItemTemplate

David Veeneman picture David Veeneman · Jan 17, 2010 · Viewed 17.4k times · Source

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.

Answer

Aviad P. picture Aviad P. · Jan 17, 2010

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>