c#为什么ListBoxItem不能显示每张图片(左侧)?

时间:2013-07-10 12:37:00

标签: c# wpf listbox listboxitems

我有一个ListBox,它应该显示每个项目的图片。我编写代码,当我运行它时,图片无法显示,但只显示文字。我的代码中我做错了什么?我确保图像文件路径是正确的。

我想用文字(右侧)和图标(左侧)显示每个项目。

WPF:

<ListBox Name="ListTest" DisplayMemberPath="Name"  HorizontalAlignment="Left" Height="358" Margin="603,38,0,0" VerticalAlignment="Top" Width="361">
</ListBox>

C#

public partial class UserControl2 : UserControl
{
    public UserControl2()
    {
        InitializeComponent();
        this.LoadLogos();
    }

    private void LoadLogos()
    {
        this.ListTest.Items.Add(new CompanyDataContext("Adobe", "Adobe is a designing tool.", "/Company Logos/testDinner.jpg"));
        this.ListTest.Items.Add(new CompanyDataContext("Facebook", "FedEx is a social networking website.", "/Company Logos/facebook.jpg"));
        this.ListTest.Items.Add(new CompanyDataContext("FedEx", "FedEx is a courier company.", "/Company Logos/fedex.jpg"));

    }

    private class CompanyDataContext
    {
        public CompanyDataContext(string name, string about, string image)
        {
            this.Name = name;
            this.About = about;
            this.Image = image;
        }

        public string Name { get; private set; }
        public string About { get; private set; }
        public string Image { get; private set; }
    }
}

1 个答案:

答案 0 :(得分:1)

你需要一个DataTemplate for CompanyDataContext,因为它不从Visual继承,WPF不知道如何渲染它,因此它调用了ToString方法。

这可以用ListBox的aDataTemplate来处理

未经测试的模板:

<ListBox.ItemTemplate>
            <DataTemplate>
                <Border x:Name="bord" CornerRadius="5" Margin="2" BorderBrush="LightGray" BorderThickness="3" Background="DarkGray">
                    <StackPanel Margin="5">
                        <TextBlock x:Name="txt" Text="{Binding Name}" FontWeight="Bold"/>
                        <Image Source="{Binding Image}" Height="100"/>
                    </StackPanel>
                </Border>

            </DataTemplate>
</ListBox.ItemTemplate>

编辑错字