以编程方式将DataGridCheckBoxColumn列添加到DataGrid

时间:2016-03-03 21:59:12

标签: c# wpf checkbox datagrid

我在我的项目中有一个xaml网格,我使用复选框我们的要求已更改,现在我们正在以编程方式构建datagrid如何在csharp中使用xaml。以下是我在xaml

中有复选框列的示例
<DataGridTemplateColumn>
    <DataGridTemplateColumn.Header>
       <CheckBox x:Name="chkHeader" />
            </DataGridTemplateColumn.Header>
                <DataGridTemplateColumn.CellTemplate>
                   <DataTemplate>
                            <CheckBox IsChecked="{Binding IsChecked,   
                           ElementName=chkHeader, Mode=OneWay,
                           UpdateSourceTrigger=PropertyChanged}"  />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>

这里以编程方式我创建了一个网格

foreach (var field in dc.AllColumns)
 {
     var binding = new Binding(".") { Converter = new  
        IndexingDataFieldsConverter(field) };
        AudioPlayBackGrid.Columns.Add(new DataGridTextColumn { Header = 
          field.Field.Description, Binding = binding});
  }

在这里我以编程方式注入复选框,到目前为止我已经在xaml中完成了

    Binding columnbinding = new Binding("IsChecked");
    columnbinding.Mode = BindingMode.OneWay;
    columnbinding.RelativeSource = new RelativeSource
    (RelativeSourceMode.FindAncestor);
    columnbinding.RelativeSource.AncestorType = datagrid.GetType();

    CheckBox chkHeader = new CheckBox();
    chkHeader.Content = "ALL";
    chkHeader.SetBinding(CheckBox.IsCheckedProperty, columnbinding);
    DataGridCheckBoxColumn checkBoxColumn = new   
    DataGridCheckBoxColumn();
    checkBoxColumn.Header = chkHeader;
    checkBoxColumn.Binding = columnbinding;
    AudioPlayBackGrid.Columns.Add(checkBoxColumn);

不知怎的,我无法在csharp中做我在xaml网格中所做的任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

您可以尝试这种方法以编程方式添加列:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    DataGridTextColumn dgTextColumn = new DataGridTextColumn();
    dgTextColumn.Header = "ID";
    dgTextColumn.Binding = new Binding("ID");
    dataGrid1.Columns.Add(dgTextColumn);

    DataGridCheckBoxColumn dgCheckBoxColumn = new DataGridCheckBoxColumn();
    dgCheckBoxColumn.Header = "IsChecked";
    dgCheckBoxColumn.Binding = new Binding("IsChecked");
    dataGrid1.Columns.Add(dgCheckBoxColumn);

    DataGridTextColumn dgTextColumn2 = new DataGridTextColumn();
    dgTextColumn2.Header = "Name";
    dgTextColumn2.Binding = new Binding("Name");
    dataGrid1.Columns.Add(dgTextColumn2);

    dataGrid1.Items.Add(new Item() { ID = 1, Name = "Someone1", IsChecked = true });
    dataGrid1.Items.Add(new Item() { ID = 2, Name = "Someone2", IsChecked = false });
    dataGrid1.Items.Add(new Item() { ID = 3, Name = "Someone3", IsChecked = true });
    dataGrid1.Items.Add(new Item() { ID = 4, Name = "Someone4", IsChecked = false });
}

模特:

public class Item
{
    public int ID { get; set; }
    public string Name { get; set; }
    public bool IsChecked { get; set; }
}