jeudi 3 mars 2016

WPF: Adding Checkbox column programatically

 I have in my project a xaml grid where I'm using checkbox
 our requirement is changed now we are constructing datagrid programatically
 how can I use xaml in csharp. following is the example I have checkbox     
 column in 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>

Here programatically I'm creating a grid 

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});
  }

and here I'm injecting check box programatically that I have in xaml so far I have done

    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);

Somehow I cannot do in csharp what I did in xaml grid any help will be appreciated




Aucun commentaire:

Enregistrer un commentaire