简体   繁体   中英

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:

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

    }
}

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM