WPF DataGrid绑定及列居中

基本的数据绑定

  把集合的字段(属性)绑定在DataGrid的Binding属性就能将数据绑定列表

1    public class CashItem {
2        public int Value { get; set; }
3        public int Count { get; set; }
4        public int Amount { get { return Value * Count; } }
5     }
1             var items = new List<CashItem>() {
2                 new CashItem{Value=100,Count=23},
3                 new CashItem{Value=50,Count=10},
4                 new CashItem{Value=20,Count=5},
5                 new CashItem{Value=10,Count=11}
6             };
7             this.Cassetters.ItemsSource = items;
1   <DataGrid Name="Cassetters" HeadersVisibility="Column" GridLinesVisibility="Horizontal" AutoGenerateColumns="False">
2       <DataGrid.Columns>
3           <DataGridTextColumn Header="面值" Width="80" Binding="{Binding Value}">
4           </DataGridTextColumn>
5           <DataGridTextColumn Header="张数" Width="80" Binding="{Binding Count}"></DataGridTextColumn>
6           <DataGridTextColumn Header="金额" Width="*" Binding="{Binding Amount}"></DataGridTextColumn>
7       </DataGrid.Columns>
8   </DataGrid>

DataGrid列居中

  列居中需要使用到了模板,但是列头的居中需要自己定义样式,数据的绑定方式和之前的一样也是通过Binding属性

 1   <DataGrid Name="Cassetters" HeadersVisibility="Column" GridLinesVisibility="Horizontal" AutoGenerateColumns="False">
 2       <DataGrid.Columns>
 3           <DataGridTextColumn Header="面值" Width="50" Binding="{Binding Value}">
 4           </DataGridTextColumn>
 5           <DataGridTextColumn Header="张数" Width="50" Binding="{Binding Count}"></DataGridTextColumn>
 6           <DataGridTextColumn Header="金额" Width="50" Binding="{Binding Amount}"></DataGridTextColumn>
 7           <DataGridTemplateColumn  Header="模板列" Width="*">
 8               <DataGridTemplateColumn.HeaderStyle>
 9                   <Style TargetType="DataGridColumnHeader">
10                       <Setter Property="HorizontalContentAlignment" Value="Center"></Setter>
11                   </Style>
12               </DataGridTemplateColumn.HeaderStyle>
13               <DataGridTemplateColumn.CellTemplate>
14                   <DataTemplate>
15                       <TextBlock HorizontalAlignment="Center" Text="{Binding Amount}"></TextBlock>
16                   </DataTemplate>
17               </DataGridTemplateColumn.CellTemplate>
18           </DataGridTemplateColumn>
19       </DataGrid.Columns>
20   </DataGrid>

posted @ 2016-04-26 17:27  高效养猪倌  阅读(13522)  评论(2编辑  收藏  举报