WPF中的Grid Panel元素是否有数据模板?

7

我对WPF还比较新...

我有一组数据,希望将其绑定到网格面板上。每个对象都包含其网格行和列,以及要填充到网格位置的内容。我非常喜欢如何在listbox XAML中创建数据模板,以便在几乎没有代码的情况下创建UI。是否有一种方法可以为网格面板元素创建数据模板,并将面板绑定到数据集合?

2个回答

16

你可以使用一个ItemsControl,并将其面板设置为Grid。以下是一个示例。XAML:

    <ItemsControl x:Name="myItems">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>
                </Grid>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding MyText}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.ItemContainerStyle>
            <Style>
                <Style.Setters>
                    <Setter Property="Grid.Row" Value="{Binding MyRow}" />
                    <Setter Property="Grid.Column" Value="{Binding MyColumn}" />
                </Style.Setters>
            </Style>
        </ItemsControl.ItemContainerStyle>
    </ItemsControl>

测试用的代码后台:

    public Window1()
    {
        InitializeComponent();
        myItems.ItemsSource = new[] {
            new {MyRow = 0, MyColumn = 0, MyText="top left"},
            new {MyRow = 1, MyColumn = 1, MyText="middle"},
            new {MyRow = 2, MyColumn = 2, MyText="bottom right"}
        };
    }

5
如果您知道要显示的行数,这种方法效果很好,但如果要根据数据量显示任意行数,则无法实现。 - LJNielsenDk
1
我试图从DataTemplate(模板中的根元素)设置行和列,想知道为什么它不起作用。这非常有帮助。谢谢! - qJake

1

不确定这是否有助于您,但为什么不尝试将 ItemsControl(ListBox、ListView)的 ItemsPanel 设置为 UniformGrid 呢?像这样:

<ItemsControl>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

这与之前的解决方案类似,只不过更加动态一些。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接