代码之家  ›  专栏  ›  技术社区  ›  tbischel

WPF中是否有网格面板元素的数据模板?

  •  5
  • tbischel  · 技术社区  · 14 年前

    对WPF来说还很陌生…

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

    2 回复  |  直到 10 年前
        1
  •  13
  •   Heinzi    14 年前

    你可以使用 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"}
            };
        }
    
        2
  •  0
  •   Carlo    14 年前

    不确定这是否对您有帮助,但为什么不尝试将itemsControl(ListBox、ListView)的itemsPanel设置为UniformGrid。像这样:

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

    它与前面的解决方案类似,只是有点更动态。