
using System.Windows.Data;
using Telerik.Windows.Controls;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace CellTemplateProblem
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        Binding binding = null;
        public MainWindow()
        {
            InitializeComponent();           
            CreateColumns();
        }

        private void CreateColumns()
        {
            var converter = new ItemConverter();

            for (int i = 0; i < 5; i++)
            {
                var column = new GridViewDataColumn
                                 {
                                     Name = "Column" + i,
                                     Header = "Column" + i,
                                     Tag = i,
                                 };


                this.binding = new Binding("Id");
                this.binding.Mode = BindingMode.TwoWay;
                this.binding.Converter = converter;
                this.binding.ConverterParameter = column;

                column.DataMemberBinding = this.binding;
                column.CellEditTemplate = this.CreateCellEditTemplate();
                column.CellTemplate = this.CreateCellTemplate();
                grid.Columns.Add(column);
            }
        }

        private Binding CloneBinding()
        {
            Binding newBinding = new Binding();
            newBinding.Converter = this.binding.Converter;
            newBinding.ConverterParameter = this.binding.ConverterParameter;
            newBinding.Path = this.binding.Path;
            newBinding.Mode = this.binding.Mode;
            return newBinding;
        }

        private DataTemplate CreateCellEditTemplate()
        {
            FrameworkElementFactory fe = new FrameworkElementFactory(typeof(TextBox));
            fe.SetValue(TextBox.ForegroundProperty, new SolidColorBrush(Colors.Red));
            fe.SetBinding(TextBox.TextProperty, this.CloneBinding());
            DataTemplate dt = new DataTemplate();
            dt.VisualTree = fe;
            dt.Seal();
            return dt;
        }

        private DataTemplate CreateCellTemplate()
        {
            FrameworkElementFactory fe = new FrameworkElementFactory(typeof(TextBlock));
            fe.SetValue(TextBlock.ForegroundProperty, new SolidColorBrush(Colors.Blue));
            fe.SetBinding(TextBlock.TextProperty, this.CloneBinding());
            DataTemplate dt = new DataTemplate();
            dt.VisualTree = fe;
            dt.Seal();
            return dt;
        }
    }
}
