WPF学习——DataTemplate

<Window x:Class="DataTemplate.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DataTemplate"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
            <ListBox x:Name="listBox" Height="200" FontSize="25" Margin="10">
                <ListBox.ItemTemplate>
                    <DataTemplate >
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding Name}"/>
                            <TextBlock Text="{Binding Age}"/>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
            <DataGrid  x:Name="dataGrid" Height="200" FontSize="25" Margin="10,0,10,10"
                       AutoGenerateColumns="False" CanUserAddRows="False" ColumnWidth="*">
                <DataGrid.Columns>
                    <DataGridTemplateColumn Header="学生信息">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal">
                                    <TextBlock Text="{Binding Name}"/>
                                    <TextBlock Text="---"/>
                                    <TextBlock Text="{Binding Age}"/>
                                </StackPanel>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                </DataGrid.Columns>
            </DataGrid>
        </StackPanel>
        
    </Grid>
</Window>
        public MainWindow()
        {
            InitializeComponent();
            List<Student> Students = new List<Student>();
            Students.Add(new Student() { Name="Andy",Age=23});
            Students.Add(new Student() { Name = "Tom", Age = 27 });
            Students.Add(new Student() { Name = "John", Age = 23 });
            Students.Add(new Student() { Name = "Zoe", Age = 25});
            this.listBox.ItemsSource = Students;
            this.dataGrid.ItemsSource = Students;

        }
        public class Student {
            public string Name { get; set; }
            public int Age { get; set; }

        }

主界面两个控件,一个ListBox,一个DataGrid,都是通过后端代码ItemsSource与Student实例绑定。

修改DataTemplate内部的代码,可以修改数据在两个表格中的呈现方式。

我这里只做了水平排列和加了“---”字符串。

posted @ 2021-07-20 16:41  李令君  阅读(217)  评论(0)    收藏  举报