0

我有一个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; }
    }
}
4

1 回答 1

1

您需要 CompanyDataContext 的 DataTemplate,因为它不是从 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>

编辑错字

于 2013-07-10T12:39:47.267 回答