更好的方法是使用数据绑定......比方说你有,你想在你的列表框中显示Person对象的列表,在代码隐藏设置列表作为的ItemsSource:
public class Person()
{
public string Name {get; set;}
}
var persons = new List<Person>();
// ... add some person objects here ...
listBox.ItemsSource = persons
在你XAML则可以提供呈现每个人作为一个按钮一个DataTemplate:
<ListBox x:Name="listBox">
<Listox.ItemTemplate>
<DataTemplate>
<Button Content={Binding Path=Name}/>
</DataTemplate>
</Listox.ItemTemplate>
</ListBox>
这将使得其显示每个人的姓名按钮的列表。
要指定每个按钮的图片来扩展你的按钮的内容包括图像:
<ListBox x:Name="listBox">
<Listox.ItemTemplate>
<DataTemplate>
<Button>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}"/>
<ImageText Source="{Binding Path=Image}"/>
</StackPanel>
</Button>
</DataTemplate>
</Listox.ItemTemplate>
</ListBox>
当然,你应得的ImageSource的属性添加到您的Person对象:
public class Person()
{
public string Name {get; set;}
public ImageSource Image {get; set;}
}
另一种替代方法是使用值转换器将人员的某些属性转换为图像:
Dynamic image source binding in silverlight
如果你不想使用绑定(我个人认为是最好的方法),你可以创建一个具有一个ImageSource的财产按下列一个按钮子类:
Creating an image+text button with a control template?