WPF Xaml中创建集合

首先在xaml中创建集合是一个不可取的方法。

本方法仅作为xaml的学习。

本文略微无聊,主要是编写的东西都是老玩意。

首先是定义一个类,作为你要加载集合的模型。

结构如下

 internal class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    internal class StudentList:List<Student>
    {

    }
  class StringCollect
    {
        public StudentList Students { get; set; }
    }

XAML中

  <Window.DataContext>
        <local:StringCollect  x:Name="c2"  >
            <local:StringCollect.Students>
                <local:StudentList>
                    <local:Student Age="18" Name="A1"/>
                    <local:Student Age="18" Name="A2"/>
                    <local:Student Age="18" Name="A3"/>
                </local:StudentList>
            </local:StringCollect.Students>
        </local:StringCollect>
    </Window.DataContext>
    <Grid>
        <ListBox ItemsSource="{Binding ElementName=c2,Path=Students}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>
                        <TextBlock>
                            <Run Text="Name:"/>
                            <Run Text="{Binding Name}"/>
                        </TextBlock>
                        <TextBlock Grid.Column="1">
                            <Run Text="Age:"/>
                            <Run Text="{Binding Age}"/>
                        </TextBlock>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>

截图如下

那么还有别的方法吗?

当然了,比如XAML中的X:Array关键字

比如

        <ListBox  >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>
                        <TextBlock>
                            <Run Text="Name:"/>
                            <Run Text="{Binding Name}"/>
                        </TextBlock>
                        <TextBlock Grid.Column="1">
                            <Run Text="Age:"/>
                            <Run Text="{Binding Age}"/>
                        </TextBlock>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.ItemsSource>
                <x:Array Type="{x:Type local:Student}">
                    <local:Student Age="18" Name="b1"/>
                    <local:Student Age="18" Name="b2"/>
                    <local:Student Age="18" Name="b3"/>
                </x:Array>
            </ListBox.ItemsSource>
        </ListBox>

我觉得在xaml创建集合是一个比较无聊的事情。

猜你喜欢

转载自www.cnblogs.com/T-ARF/p/11484002.html