更好的方法是使用数据绑定...例如,您有一个要在列表框中显示的 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;}
}
另一种方法是使用值转换器将 Person 的某些属性转换为图像:
Dynamic image source binding in silverlight
如果您不想使用绑定(我个人认为这是最好的方法),您可以创建一个具有 ImageSource 属性的 Button 子类,如下所示:
Creating an image+text button with a control template?