将图像添加到列表框 [英] Add image to listbox
本文介绍了将图像添加到列表框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些带有一些文字的图片,我需要在列表框中显示带有相关文字的图片。
I have a few images with some text, I need to show the image with the relevant text in a listbox.
浏览谷歌我遇到了这个样本班,
Browsing google I came across this sample class,
public class Customer
{
public string Fname;
public string Lname;
public Customer(string firstName, string lastName)
{
Fname = firstName;
Lname = lastName;
}
public override string ToString()
{
return Fname + " " + Lname;
}
}
lstCustomers.Items.Add(new Customer("Foo","Bar"));
上面的代码工作正常,因为它只返回字符串,如何将图像和字符串一起返回以便它被添加到列表框中?
The above code works fine as it only returns string, how do I return an image and a string together so that it gets added to the listbox?
最好的问候
@nand
推荐答案
只需使用 DataTemplate
在 ListBox中显示对象
。
创建一个包含字符串属性和Image属性的数据对象:
Create a data object that contains string properties and an Image property:
public class Img
{
public Img(string value, Image img) { Str = value; Image = img; }
public string Str { get; set; }
public Image Image { get; set; }
}
创建 DataTemplate
显示:
<ListBox x:Name="lstBox">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type local:Img}">
<StackPanel>
<TextBlock Margin="3" Text="{Binding Str}"/>
<ContentControl Margin="3" Content="{Binding Image}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
现在添加 Img
项目(或者你的数据对象)到 ListBox
,如下所示:
Now add the Img
items (or your data objects) to the ListBox
like so:
lstBox.Items.Add(new Img("Value", myImage));
这篇关于将图像添加到列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文