简体   繁体   English

C#WPF DataGrid.ItemsSource生成新列

[英]C# WPF DataGrid.ItemsSource generates new Columns

I use a DataTable as source for my DataGrid: 我使用DataTable作为DataGrid的源代码:

  dt.Columns.Add("Update?", typeof(Boolean));
  dt.Columns.Add("Emulator", typeof(String));
  dt.Columns.Add("Path", typeof(String));

  ...      

  dataGrid1.ItemsSource = dt.DefaultView;

The XAML code to the DataGrid: DataGrid的XAML代码:

     <DataGrid  AutoGenerateColumns="True" Height="133" HorizontalAlignment="Left" Margin="0,81,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="688"  >
        <DataGrid.Columns>
            <DataGridCheckBoxColumn CanUserResize="False" Header="Update?" />
            <DataGridTextColumn CanUserResize="False" Header="Emulator" IsReadOnly="False"/>
            <DataGridTextColumn CanUserResize="False" Header="Path" IsReadOnly="False"/>
        </DataGrid.Columns>
    </DataGrid>

So if the DataTable is empty I got an empty DataGrid showing the three headers names. 因此,如果DataTable为空,我会得到一个空的DataGrid,显示三个标题名称。
If the DataTable contains items the DataGrid gets extra columns instead of filling the already existing ones. 如果DataTable包含项,则DataGrid会获取额外的列,而不是填充已存在的列。

在此输入图像描述

What can I do that the DataGrid fills up its existing columns? DataGrid如何填充现有列?

set AutoGenerateColumns="False" 设置AutoGenerateColumns="False"

if you set this property as true the columns will be created automatically 如果将此属性设置为true ,则将自动创建列

And also you need to set the binding , sample code : 而且你还需要设置绑定,示例代码:

<DataGrid Name="DG1" AutoGenerateColumns="False" ItemsSource="{Binding}">
    <DataGrid.Columns>
        <DataGridCheckBoxColumn Header="Online Order?" IsThreeState="True" Binding="{Binding OnlineOrderFlag}" />
    </DataGrid.Columns>
</DataGrid>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM