WPF:列表框中的图像路径,显示图像代替路径
我有一个列表框,其中填充了不同图像的路径。我将如何更改 ItemTemplate 以便显示图像而不是路径(字符串)。
这是代码:
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<Image Height="50" Width="50" Source="{Binding Path=Content}" Stretch="Fill"></Image>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBoxItem>C:\Users\AKSHAY\Pictures\IMG0083A.jpg</ListBoxItem>
<ListBoxItem>C:\Users\AKSHAY\Pictures\IMG0102A.jpg</ListBoxItem>
<ListBoxItem>C:\Users\AKSHAY\Pictures\IMG0103A.jpg</ListBoxItem>
<ListBoxItem>C:\Users\AKSHAY\Pictures\IMG0104A.jpg</ListBoxItem>
<ListBoxItem>C:\Users\AKSHAY\Pictures\IMG0105A.jpg</ListBoxItem>
<ListBoxItem>C:\Users\AKSHAY\Pictures\IMG0106A.jpg</ListBoxItem>
</ListBox>
I have a ListBox filled with paths of different images. How will I alter the ItemTemplate so that the images will be shown instead of paths(string).
Here is the code:
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<Image Height="50" Width="50" Source="{Binding Path=Content}" Stretch="Fill"></Image>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBoxItem>C:\Users\AKSHAY\Pictures\IMG0083A.jpg</ListBoxItem>
<ListBoxItem>C:\Users\AKSHAY\Pictures\IMG0102A.jpg</ListBoxItem>
<ListBoxItem>C:\Users\AKSHAY\Pictures\IMG0103A.jpg</ListBoxItem>
<ListBoxItem>C:\Users\AKSHAY\Pictures\IMG0104A.jpg</ListBoxItem>
<ListBoxItem>C:\Users\AKSHAY\Pictures\IMG0105A.jpg</ListBoxItem>
<ListBoxItem>C:\Users\AKSHAY\Pictures\IMG0106A.jpg</ListBoxItem>
</ListBox>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以制作一个 IValueConverter 将字符串转换为 ImageSource。
类似于:
然后创建一个值转换器资源并在您的绑定中使用它。
资源可以这样定义:
然后绑定:
You could make an IValueConverter that converts a string to a ImageSource.
Something like:
And then create a value converter resource and use that in your binding.
a resource could be defined like:
and then bind with:
在 UI 生成期间,
ListBox
的ItemTemplate
被复制到ListBoxItem
的ContentTemplate
。但是,直接添加ListBoxItem
时,对于已属于ItemsControl
容器类型的项目(ListBoxItem
),将忽略ItemTemplate
> 用于ListBox
,ListViewItem
用于ListView
等)。因此,在这种情况下,您必须直接使用ItemContainerStyle
的 ContentTemplate。另外,将
Source="{Binding Content}"
更改为Source="{Binding}"
The
ItemTemplate
of aListBox
is copied to theContentTemplate
of aListBoxItem
during UI generation. However, when adding theListBoxItem
s directly,ItemTemplate
is ignored for items already of theItemsControl
s container type (ListBoxItem
forListBox
,ListViewItem
forListView
etc.). So in this case, you'll have to use the ContentTemplate of theItemContainerStyle
directly instead.Also, change
Source="{Binding Content}"
toSource="{Binding}"
您必须在绑定中使用值转换器并传递位图图像
You have to use a value converter in the binding and pass a bitmap image