Предположим, у нас есть класс Employee
, для каждого сотрудника мы сохраняем его имя и изображение следующим образом:
public class Employee
{
public string Image { get; set; }
public string Name { get; set; }
}
Вместо Style
вам нужно использовать ItemTemplate
следующим образом:
<Window x:Class="ProofOfConcept.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox ItemsSource="{Binding}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="TextBlock.Foreground"
Value="Green"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="TextBlock.Foreground"
Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<Image Stretch="UniformToFill" Height="24"
Width="24" Margin="2,1"
Source="{Binding Image}"/>
<TextBlock Text="{Binding Name}"
VerticalAlignment="Center"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
ваш код будет выглядеть примерно так:
using System.Windows;
namespace ProofOfConcept
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var emps =
new Employee[]
{
new Employee {Image = "/Images/1.png", Name = "Mohamed A. Fadil"},
new Employee {Image = "/Images/6.png", Name = "Sara Konor :)"},
new Employee {Image = "/Images/2.png", Name = "John M. Arther"},
new Employee {Image = "/Images/3.png", Name = "Khalid El-Sheikh"},
new Employee {Image = "/Images/4.png", Name = "Hassan A. Fadil"},
new Employee {Image = "/Images/5.png", Name = "Criss Redfield"}
};
DataContext = emps;
}
}
}
И, наконец, результат: D