Displaying images in grid with WPF

左心房为你撑大大i 提交于 2019-12-03 21:43:24

问题


I'm creating an application with a store inside of it, so I need a grid view for items' icons with text. iTunes gives a good example of what I need. Any ideas?

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


回答1:


You could use a ListBox that has a WrapPanel for its panel type, then use a DataTemplate that uses an Image element for the icon and a TextBlock for their caption.

EG:

public class MyItemType
{
    public byte[] Icon { get; set; }

    public string Title { get; set; }
}

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

When loading the icon, refer to Microsoft's Imaging Overview since there are a lot of ways to do it.

Then in 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>


来源:https://stackoverflow.com/questions/5236252/displaying-images-in-grid-with-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!