使用WPF在网格中显示图像

Eli*_*zar 3 c# wpf grid image

我正在创建一个带有商店的应用程序,所以我需要一个带有文本的项目图标的网格视图.iTunes提供了我需要的一个很好的例子.有任何想法吗?

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

Chr*_*ham 12

您可以使用ListBox具有WrapPanelfor其面板类型的a,然后使用DataTemplate,该Image元素使用图标元素和TextBlock作为其标题.

例如:

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

    public string Title { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在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;
}
Run Code Online (Sandbox Code Playgroud)

加载图标时,请参阅Microsoft的"成像概述",因为有很多方法可以执行此操作.

然后在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>
Run Code Online (Sandbox Code Playgroud)