2017-03-29 114 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