Hi @Luca Iovene , Welcome to Microsoft Q&A,
Dynamically create the DataTemplate of DataGridTemplateColumn in C#, without relying on XAML, and use FrameworkElementFactory to build the template content. You can dynamically generate a DataTemplate for DataGridTemplateColumn and define different UI elements for each cell.
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace _xxx
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DynamicDataGrid dynamicDataGrid = new DynamicDataGrid();
DataGrid dataGrid = dynamicDataGrid.CreateDataGrid();
MainGrid.Children.Add(dataGrid);
List<MyData> data = new List<MyData>
{
new MyData { Value = "Item 1" },
new MyData { Value = "Item 2" },
new MyData { Value = "Item 3" }
};
dataGrid.ItemsSource = data;
}
public class MyData
{
public string Value { get; set; }
}
///Programmatically assign a UserControl to a DataTemplate
public class DynamicDataGrid
{
public DataGrid CreateDataGrid()
{
DataGrid dataGrid = new DataGrid();
DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
templateColumn.Header = "Dynamic Column";
DataTemplate cellTemplate = new DataTemplate();
FrameworkElementFactory textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));
Binding binding = new Binding("Value");
textBlockFactory.SetBinding(TextBlock.TextProperty, binding);
cellTemplate.VisualTree = textBlockFactory;
templateColumn.CellTemplate = cellTemplate;
dataGrid.Columns.Add(templateColumn);
return dataGrid;
}
}
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.