Reputation: 39
I have the following database: and I would like to display all employees and their pictures in a listbox. Whenever I run my code, I receive an System.InvalidOperationException at this part of the code:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var list = db.Employees;
list.Load();
liemp.ItemsSource = list.Local.OrderBy(l => l.LastName);
}
This is my WPF code:
<Window x:Class="NorthwindWPF.employeeList"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:NorthwindWPF"
mc:Ignorable="d"
Loaded="Window_Loaded"
Title="employeeList" Height="350" Width="300">
<Grid>
<ListBox x:Name="liemp"
DisplayMemberPath="FirstName"
SelectedValuePath="EmployeeID">
<Image Source="{Binding PhotoPath}" />
</ListBox>
</Grid>
</Window>
And this is my class code:
namespace NorthwindWPF
{
/// <summary>
/// Interaction logic for employeeList.xaml
/// </summary>
public partial class employeeList : Window
{
NorthwindEntities db = new NorthwindEntities();
public employeeList()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var list = db.Employees;
list.Load();
liemp.ItemsSource = list.Local.OrderBy(l => l.LastName);
}
}
}
Upvotes: 0
Views: 791
Reputation: 128062
You have directly added a single Image
item to the ListBox.
<ListBox ...>
<Image Source="{Binding PhotoPath}" /> <!-- here -->
</ListBox>
Subsequently setting the ListBox's ItemsSource
will then fail with an InvalidOperationException
.
Instead of setting the ListBox's DisplayMemberPath
property, you should define its ItemTemplate
like this:
<ListBox x:Name="liemp" SelectedValuePath="EmployeeID">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding PhotoPath}"/>
<TextBlock Text="{Binding FirstName}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Upvotes: 1