Here is the code to add a DataGridTemplateColumn programmatically.
http://social.msdn.microsoft.com/Forums/en/wpf/thread/df77a277-91d4-41f1-a42a-0fa02a443ff4
DataGridTemplateColumn imgColumn = new DataGridTemplateColumn(); imgColumn.Header = "Image"; FrameworkElementFactory imageFactory = new FrameworkElementFactory(typeof(Image)); imageFactory.SetBinding(Image.SourceProperty, new Binding("ImgPath")); DataTemplate dataTemplate = new DataTemplate(); dataTemplate.VisualTree = imageFactory; imgColumn.CellTemplate = dataTemplate; DGImages.Columns.Add(imgColumn);
I also added the source code for the sample application that I created. Hope this helps.
MainWindow.xaml File
<Window x:Class="StackOverflow.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <DataGrid Name="DGImages" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="Image Desc" Binding="{Binding ImgDesc}"></DataGridTextColumn> </DataGrid.Columns> </DataGrid> </Grid> </Window>
MainWindow.xaml.cs file
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Collections.ObjectModel; namespace StackOverflow {
SampleClass.cs File
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; namespace StackOverflow { public class SampleClass : INotifyPropertyChanged { private string _ImgDesc; public string ImgDesc { get { return _ImgDesc; } set { _ImgDesc = value; OnPropertyChanged("ImgDesc"); } } private string _ImgPath; public string ImgPath { get { return _ImgPath; } set { _ImgPath = value; OnPropertyChanged("ImgPath"); } } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
source share