DataGridTemplateColumn:在使用ItemsSource之前,Items集合必须为空。

时间:2011-07-30 09:35:24

标签: wpf datagrid binding datagridtemplatecolumn

为什么是错误代码:

        <dg:DataGrid  Name="dataGrid" AutoGenerateColumns="False"                                  
                HeadersVisibility="Column" SelectedIndex="-1" Margin="0,315,0,0" Background="#FF484040" BorderBrush="#FF484040">
        <dg:DataGrid.Columns>
            <dg:DataGridTextColumn Binding="{Binding IdBook}" Header="IdBook"></dg:DataGridTextColumn>
            <dg:DataGridTextColumn Binding="{Binding NameBook}" Header="NameBook"></dg:DataGridTextColumn>
            <dg:DataGridTextColumn Binding="{Binding Author}" Header="Author"></dg:DataGridTextColumn>
        </dg:DataGrid.Columns>

        <dg:DataGridTemplateColumn Header="Delete">

            <dg:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Style="{DynamicResource GlassButton}" Background="{DynamicResource DeleteButton}">

                    </Button>
                </DataTemplate>
            </dg:DataGridTemplateColumn.CellTemplate>

            </dg:DataGridTemplateColumn>
    </dg:DataGrid>

以下代码是正确的:

        <dg:DataGrid  Name="dataGrid" AutoGenerateColumns="False"                                  
                HeadersVisibility="Column" SelectedIndex="-1" Margin="0,315,0,0" Background="#FF484040" BorderBrush="#FF484040">
        <dg:DataGrid.Columns>
            <dg:DataGridTextColumn Binding="{Binding IdBook}" Header="IdBook"></dg:DataGridTextColumn>
            <dg:DataGridTextColumn Binding="{Binding NameBook}" Header="NameBook"></dg:DataGridTextColumn>
            <dg:DataGridTextColumn Binding="{Binding Author}" Header="Author"></dg:DataGridTextColumn>
        </dg:DataGrid.Columns>

    </dg:DataGrid>

但我不能将按钮添加到datagrid

1 个答案:

答案 0 :(得分:36)

将模板列保留在DataGrid.Columns中。

     <dg:DataGrid  Name="dataGrid" AutoGenerateColumns="False"                                  
            HeadersVisibility="Column" SelectedIndex="-1" Margin="0,315,0,0" Background="#FF484040" BorderBrush="#FF484040">
    <dg:DataGrid.Columns>
        <dg:DataGridTextColumn Binding="{Binding IdBook}" Header="IdBook"></dg:DataGridTextColumn>
        <dg:DataGridTextColumn Binding="{Binding NameBook}" Header="NameBook"></dg:DataGridTextColumn>
        <dg:DataGridTextColumn Binding="{Binding Author}" Header="Author"></dg:DataGridTextColumn>
       <dg:DataGridTemplateColumn Header="Delete">
             <dg:DataGridTemplateColumn.CellTemplate>
                 <DataTemplate>
                       <Button Style="{DynamicResource GlassButton}" Background="{DynamicResource DeleteButton}">
                         </Button>
            </DataTemplate>
        </dg:DataGridTemplateColumn.CellTemplate>
        </dg:DataGridTemplateColumn>
    </dg:DataGrid.Columns>
  </<dg:DataGrid>