使用WPF在网格中显示图像

3

我正在创建一个带有商店的应用程序,因此需要一个包含文本的项目图标网格视图。iTunes提供了一个很好的示例。有什么想法吗?

http://i55.tinypic.com/16jld3a.png

1个回答

12
你可以使用一个具有 WrapPanel 面板类型的 ListBox,然后使用一个使用 Image 元素作为图标和 TextBlock 作为标题的 DataTemplate。
例如:
public class MyItemType
{
    public byte[] Icon { get; set; }

    public string Title { get; set; }
}

在 window.xaml.cs 中:

public List<MyItemType> MyItems { get; set; }

public Window1()
{
    InitializeComponent();

    MyItems = new List<MyItemType>();
    MyItemType newItem = new MyItemType();
    newItem.Image = ... load BMP here ...;
    newItem.Title = "FooBar Icon";
    MyItems.Add(newItem);

    this.MainGrid.DataContext = this;
}

加载图标时,请参考Microsoft的Imaging Overview,因为有很多种方法可以做到。

然后在window.xaml中:

<Window x:Class="MyApplication.Window1"
    xmlns:local="clr-namespace:MyApplication"
>

<Window.Resources>
    <DataTemplate DataType="{x:Type local:MyItemType}">
       <StackPanel>
           <Image Source="{Binding Path=Icon}"/>
           <TextBlock Text="{Binding Path=Title}"/>
       </StackPanel>
    </DataTemplate>
</Window.Resources>

<Grid Name="MainGrid">
    <ListBox ItemsSource="{Binding Path=MyItems}">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel IsItemsHost="True"/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
    </ListBox>
</Grid>

我对我的示例进行了更详细的展开,这有帮助吗? - Chris Wenham
我尝试将这个示例绑定到我的代码,但出现了问题“local:MyItemType未找到”。另外,你能描述一下MyItems.Add是如何工作的吗? - Eliazar
本地命名空间只需要在<Window>元素中声明:请参见答案的编辑--一旦您键入“xmlns:local =”,智能感知就会弹出,然后您可以从中选择应用程序的命名空间。在示例中,MyItems是List的一个实例,.Add()方法只是向其中添加一个新项。由于有很多加载图像的方式,我链接到了Microsoft的Imaging概述,以便让您有一个想法。 - Chris Wenham
@Eliazar - 你需要将其替换为你正在绑定到列表框的项目类型。 - RQDQ
现在没有错误,但是列表框没有出现。我已经使用了这个转换器来处理bmp格式的图像。 MemoryStream mstream = new MemoryStream(); Bitmap bitmap1 = new Bitmap(@"C:\Users\Eliazar\Pictures\1556.bmp"); bitmap1.Save(mstream, System.Drawing.Imaging.ImageFormat.Bmp); byte[] byte1 = mstream.ToArray(); BinaryWriter writer = new BinaryWriter(mstream); writer.Write(byte1); - Eliazar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接