我有以下数据库:http://merc.tv/img/fig/Northwind_diagram.jpg我希望在列表框中显示所有员工及其图片。每当我运行我的代码时,我会在代码的这一部分收到System.InvalidOperationException:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var list = db.Employees;
list.Load();
liemp.ItemsSource = list.Local.OrderBy(l => l.LastName);
}
这是我的WPF代码:
<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>
这是我的班级代码:
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);
}
}
}
答案 0 :(得分:1)
您已直接向ListBox添加了一个Image
项。
<ListBox ...>
<Image Source="{Binding PhotoPath}" /> <!-- here -->
</ListBox>
随后设置ListBox的ItemsSource
将失败并显示InvalidOperationException
。
您应该像这样定义DisplayMemberPath
,而不是设置ListBox的ItemTemplate
属性:
<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>