2017-03-29 90 views
0

我有以下数据库:http://merc.tv/img/fig/Northwind_diagram.jpg,我想在列表框中显示所有员工及其图片。每当我跑我的代码,我收到一个System.InvalidOperationException在这部分代码:从数据库中显示图片WPF

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); 
     } 

    } 
} 

回答

1

您已将一个Image项目直接添加到列表框中。

<ListBox ...> 
    <Image Source="{Binding PhotoPath}" /> <!-- here --> 
</ListBox> 

随后的设置,然后ListBox的ItemsSource将与InvalidOperationException失败。

而不是设置ListBox的DisplayMemberPath财产,你应该定义其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> 
+0

出于某种原因,程序冻结,我在图像路径现在看起来,我想它们是无效的:HTTP:/ /accweb/emmployees/davolio.bmp – Michael

+0

他不应该使用'ObservableCollection'作为'liemp'的'DataSource'吗? – Everyone

+0

@Everyone出于什么原因?显然,ItemsSource属性被设置为一个固定的集合。除此之外,这里没有'DataSource'。 – Clemens