[英]Display image in WPF from database
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:
每当我运行我的代码时,我都会在代码的这一部分收到 System.InvalidOperationException:
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:这是我的 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>
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);
}
}
}
You have directly added a single Image
item to the ListBox.您已直接将单个
Image
项添加到 ListBox。
<ListBox ...>
<Image Source="{Binding PhotoPath}" /> <!-- here -->
</ListBox>
Subsequently setting the ListBox's ItemsSource
will then fail with an InvalidOperationException
.随后设置 ListBox 的
ItemsSource
将失败并显示InvalidOperationException
。
Instead of setting the ListBox's DisplayMemberPath
property, you should define its ItemTemplate
like this:您应该像这样定义它的
ItemTemplate
,而不是设置 ListBox 的DisplayMemberPath
属性:
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.