Hi, try this MVVM demo to add column by code. Include System.Windows.Interactivity from Nuget.
<Window x:Class="WpfApp1.Window49"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp49"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
mc:Ignorable="d"
Title="Window49" Height="450" Width="800">
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<Grid>
<DataGrid ItemsSource="{Binding View}" AutoGenerateColumns="False">
<i:Interaction.Behaviors>
<local:DataGridBehavior/>
</i:Interaction.Behaviors>
</DataGrid>
</Grid>
</Window>
--------------------------------------------------------
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Interactivity;
using System.Windows.Media;
namespace WpfApp49
{
public class ViewModel
{
public List<Data> View { get => GetData(); }
private List<Data> GetData()
{
var l = new List<Data>();
for (int i = 0; i < 10; i++) l.Add(new Data() { ID = i });
return l;
}
public class Data
{
public int ID { get; set; }
public bool Switch { get; set; } = true;
}
}
public class DataGridBehavior : Behavior<DataGrid>
{
protected override void OnAttached()
{
AssociatedObject.Columns.Add(new DataGridTextColumn() { Header = "ID", Binding = new Binding("ID") });
var dgcbc = new DataGridCheckBoxColumn() { Header = "Switch", Binding = new Binding("Switch") };
AssociatedObject.Columns.Add(dgcbc);
var st = new Style() { TargetType = typeof(DataGridCell) };
st.Setters.Add(new Setter() { Property = DataGridCell.LayoutTransformProperty, Value = new ScaleTransform() { ScaleX = 2, ScaleY = 2 } });
dgcbc.CellStyle = st;
}
}
}