WPF:ItemsControl中的行和列

时间:2018-02-16 18:42:24

标签: c# wpf xaml itemscontrol

通过设置ListViewItemsControl为{{1}的网格,我尝试将RowDefinitionsColumnDefinitions的子项放在行和列中属性。

但是,当我输入

时,子控件始终与第1行和第1列对齐
ItemsPanel

我该如何使这项工作?谢谢。

2 个答案:

答案 0 :(得分:1)

在'ItemTemplate'中设置'Grid'而不是'ItemPanel'。请参阅此处的示例: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>

答案 1 :(得分:1)

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

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