23

我是 WPF 编程的初学者,来自 .NET 2.0 C#。

我试图做一个水平的StackPanel,应该用数据库中的表中的数据填充。问题是我希望它显示带有下表中一些文本的图像,然后水平堆叠这两个项目。

这是一些伪代码来显示我想要做的事情:

<StackPanel Orientation="horizontal" ItemsSource="{Binding Path=myTable}">
    <StackPanel>
        <Image Source="User.png"/>
        <Label HorizontalAlignment="Center" Content="{Binding Path=UserName}"></Label>
    </StackPanel>
</StackPanel>

我根本不知道该怎么做。

4

2 回答 2

34

Julien 的回答对于您的书面描述是正确的,但是,查看您的 XAML,您似乎正在寻找类似以下内容:

<DataTemplate x:Key="UserDataTemplate">
    <StackPanel>
        <Image Source="User.png"/>
        <Label HorizontalAlignment="Center" Content="{Binding Path=UserName}" />
    </StackPanel>
</DataTemplate>

<ItemsControl x:Name="UserList" ItemTemplate="{StaticResource UserDataTemplate}" >
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

您肯定需要一个 ItemsControl (或一些派生)来将您的源绑定到。然后你可以通过设置它的项目面板来改变方向(我相信它是一个默认垂直方向的 VirtualizingStackPanel)所以只需将它设置为一个水平方向的 VirtualizingStackPanel。然后,您可以将每个项目的 ItemsTemplate 设置为您想要的布局(堆叠在从数据库绑定的文本顶部的图像)。

于 2009-10-06T14:18:35.300 回答
29

基本上,您希望使用能够显示对象枚举的控件。能够做到这一点的控件是类ItemsControl及其所有后代(SelectorListBoxListView等)。

将此控件的属性绑定ItemsSource到您想要的对象列表,这里是您从数据库中获取的用户列表。将ItemTemplate控件的设置为DataTemplate将用于显示列表中每个项目的 a。

示例代码:

在一个Resources部分(例如Window.Resources):

<DataTemplate x:Key="UserDataTemplate">
  <StackPanel Orientation="Horizontal">
    <Image Source="User.png"/>
    <Label HorizontalAlignment="Center" Content="{Binding Path=UserName}" />
  </StackPanel>
</DataTemplate>

在你的Window/ Page/ UserControl

<ItemsControl x:Name="UserList" ItemTemplate="{StaticResource UserDataTemplate}" />

在您后面的代码中:

UserList.ItemsSource = ... // here, an enumeration of your Users, fetched from your db
于 2009-10-06T13:20:31.600 回答