WPF:将图像添加到ListBox ItemTemplate

Dav*_*man 5 wpf listbox image itemtemplate wpf-controls

我正在创建一个带有列表框的WPF应用程序,我将绑定到项目名称.作为一个装饰元素,我想在列表中的每个项目旁边放置一个小图标,类似于Outlook在其"个人文件夹"列表中的方式.对于初学者,我将对列表中的所有项目使用相同的图像.

这是我到目前为止的标记(我会在它工作后将其移动到资源字典中):

<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>
Run Code Online (Sandbox Code Playgroud)

我在图像资源中有错误,但我不确定如何修复它.有什么建议?谢谢.

Avi*_* P. 11

Source的物业Image类型是ImageSource不是ImageBrush.以下应该有效:

<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>
Run Code Online (Sandbox Code Playgroud)