【问题标题】:Display image in WPF from database在 WPF 中显示数据库中的图像
【发布时间】:2017-03-29 17:47:49
【问题描述】:

我有以下数据库: 我想在列表框中显示所有员工及其照片。每当我运行我的代码时,我都会在这部分代码中收到 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);
        }

    }
}

【问题讨论】:

    标签: c# wpf database image exception


    【解决方案1】:

    您已将单个 Image 项目直接添加到 ListBox。

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

    随后设置 ListBox 的 ItemsSource 将失败并返回 InvalidOperationException

    您应该像这样定义它的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>
    

    【讨论】:

    • 由于某种原因程序冻结,我现在查看了图像路径,我猜它们是无效的:accweb/emmployees/davolio.bmp
    • 他不应该使用ObservableCollection 作为DataSourceliemp 吗?
    • @Everyone 出于什么原因?显然 ItemsSource 属性被设置为一个固定的集合。除此之外,这里没有DataSource
    • @Michael 您可以编写一个绑定转换器,将相对路径转换为 ​​ImageSource。
    • @Clemens 感谢您的回答。
    猜你喜欢
    • 2013-08-28
    • 2016-04-28
    • 2013-08-21
    • 1970-01-01
    • 2016-12-06
    • 2012-05-27
    相关资源
    最近更新 更多