将DataTable绑定到DataGrid

时间:2014-12-10 14:22:05

标签: c# wpf xaml datatable

XAML:

<DataGrid x:Name="grid1" AlternatingRowBackground="AliceBlue" AlternationCount="2" AutoGenerateColumns="False" HorizontalAlignment="Left"  Margin="10,51,0,0" VerticalAlignment="Top" Width="762" Height="480"   GridLinesVisibility="None"  />

代码:

DataTable dt = new DataTable();
          dt.Columns.Add("family");
          dt.Columns.Add("fund");
          dt.Rows.Add("XXX-C", "XXX");
          dt.Rows.Add("DDD-C", "DDD"); grid1.ItemsSource = dt.DefaultView;  

运行代码后,我只得到空网格,没有col标题没有行日期。但我仍然看到2个空行(代表表中的2个项目)

我在这里想念的是什么?

1 个答案:

答案 0 :(得分:1)

您指定了AutoGenerateColumns =&#34; False&#34;在DataGrid定义中,不指定任何DataGridColumns。手动指定列或设置AutoGenerateColumns =&#34; True&#34;。

<DataGrid x:Name="grid1" 
          AlternatingRowBackground="AliceBlue" 
          AlternationCount="2" 
          AutoGenerateColumns="False" 
          HorizontalAlignment="Left"  
          Margin="10,51,0,0" 
          VerticalAlignment="Top" 
          Width="762" 
          Height="480"   
          GridLinesVisibility="None">
    <DataGrid.Columns>
      <DataGridTextColumn Header="Family"
                          Binding="{Binding family}"/>
      <DataGridTextColumn Header="Fund"
                          Binding="{Binding fund}"/>
    </DataGrid.Columns>
  </DataGrid>