WPF:ItemsControl 中的行和列

WPF: rows and columns in an ItemsControl

我试过将 ListViewItemsControl 的子项放在行和列中,方法是将 RowDefinitionsColumnDefinitions 的网格设置为 ItemsPanel 属性.

然而,当我放置

时,子控件始终与第 1 行和第 1 列对齐
<ItemsControl>

   <ItemsControl.ItemsPanel>
      <!-- Grid with rows & columns ... -->
   </ItemsControl.ItemsPanel>

   <ItemsControl.ItemTemplate>
      <DataTemplate>
         <TextBlock Grid.Row="4" Grid.Column="2" ... />
      </DataTemplate>
   </ItemsControl.ItemTemplate>

</ItemsControl>

我怎样才能完成这项工作?谢谢。

在“ItemTemplate”而不是“ItemPanel”中设置“Grid”。请参阅此处的示例:http://www.wpf-tutorial.com/list-controls/itemscontrol/


public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        PersonCollection = new ObservableCollection<Person>()
        {
            new Person() { FirstName = "John", LastName = "Doe" },
            new Person() { FirstName = "Richard", LastName = "Bryson" },
            new Person() { FirstName = "Bill", LastName = "Gates" },
            new Person() { FirstName = "Adam", LastName = "Sandler" }
        };
        itemsControl.ItemsSource = PersonCollection;
    }
    public ObservableCollection<Person> PersonCollection { get; set; }
}

<ItemsControl x:Name="itemsControl">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid Margin="0,0,0,5">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <TextBlock Grid.Column="0" Text="{Binding Path=FirstName}" />
                <TextBlock Grid.Column="1" Text="{Binding Path=LastName}" />
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

您应该设置包装 ItemTemplate 根元素的容器的 Grid.RowGrid.Column 附加属性:

<ItemsControl x:Name="iccc">

    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
            </Grid>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock>cell 2:2...</TextBlock>
        </DataTemplate>
    </ItemsControl.ItemTemplate>

    <ItemsControl.ItemContainerStyle>
        <Style TargetType="ContentPresenter">
            <Setter Property="Grid.Row" Value="1" />
            <Setter Property="Grid.Column" Value="1" />
        </Style>
    </ItemsControl.ItemContainerStyle>

</ItemsControl>