DataTemplate作用是布局+数据绑定
使用DataTemplate
同时完成样式布局和数据绑定
<Window.Resources>
<DataTemplate x:Key="PersonDataTemplate">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Name}"></TextBlock>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Age}"></TextBlock>
<TextBlock Grid.Row="1" Grid.Column="0" Text="{Binding Hometown}"></TextBlock>
</Grid>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox ItemsSource="{Binding}" ItemTemplate="{StaticResource PersonDataTemplate}"></ListBox>
</Grid>
数据在后台赋值DataContext
效果
1不使用DataTemplate
也可以不使用DataTemplate,使用表格控件中的"列"(DataGrid同)
<ListView HorizontalContentAlignment="Center" VerticalContentAlignment="Center" ItemsSource="{Binding }" HorizontalAlignment="Left" Name="listView1" VerticalAlignment="Top">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Header="姓名" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Header="年龄" DisplayMemberBinding="{Binding Age}"/>
<GridViewColumn Header="年龄" DisplayMemberBinding="{Binding Hometown}"/>
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
示例代码
https://github.com/zLulus/NotePractice/tree/dev3/WPF/WpfDemo/Template/DataTemplate
DataTemplate和ControlTemplate混用
针对ListBox等表格式控件
整个ListBox采用ControlTemplate,制订外观
里面的每一项采用DataTemplate,设置外观+数据绑定
网友评论