有没有在WPF网格面板元素一个DataTemplate? [英] is there a datatemplate for grid panel elements in WPF?

查看:140
本文介绍了有没有在WPF网格面板元素一个DataTemplate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相当新的WPF ...

Fairly new to WPF...

我有一个数据集合,我想绑定到一个网格面板。每个对象都包含其网格的行和列,以及填充在网格位置填充。我真的很喜欢我怎么能在列表框中XAML创建数据模板来创建具有几乎没有背后的代码,它的UI。有没有一种方法来创建网格面板元素的数据模板,并绑定面板数据采集?

I have a collection of data I would like to bind to a grid panel. Each object contains its grid row and column, as well as stuff to fill in at the grid location. I really like how I can create data templates in the listbox XAML to create a UI with almost nothing in the code behind for it. Is there a way to create a data template for grid panel elements, and bind the panel to a data collection?

推荐答案

可以使用的ItemsControl 电网作为它的面板。下面是一个例子。 XAML:

You can use an ItemsControl with a Grid as its panel. Here is an example. 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>



代码隐藏(用于测试目的):

Codebehind (for testing purposes):

    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"}
        };
    }

这篇关于有没有在WPF网格面板元素一个DataTemplate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆