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

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,
                                     DataType = typeof(RowItem)
                                 };

                //column.CellEditTemplate = this.CreateCellEditTemplate(column);
                //column.CellTemplate = this.CreateCellTemplate(column);
                column.DataMemberBinding = new Binding(".");
                column.CellTemplate = this.Resources["dt"] as DataTemplate;
                grid.Columns.Add(column);
            }
        }

        private void TextBox_Loaded(object sender, RoutedEventArgs e)
        {
            (sender as TextBlock).SetBinding(FrameworkElement.DataContextProperty, new Binding() { Converter = new ItemConverter(), ConverterParameter = (sender as FrameworkElement).ParentOfType<GridViewCell>().Column });
        }    

        //private DataTemplate CreateCellEditTemplate(GridViewBoundColumnBase column)
        //{
        //    FrameworkElementFactory fe = new FrameworkElementFactory(typeof(TextBox));
        //    fe.SetValue(TextBox.ForegroundProperty, new SolidColorBrush(Colors.Red));
        //    fe.SetBinding(TextBox.DataContextProperty, new Binding() {Converter = new ItemConverter(), ConverterParameter =  column});
        //    fe.SetBinding(TextBox.TextProperty, new Binding("Value"));
        //    DataTemplate dt = new DataTemplate();
        //    dt.VisualTree = fe;
        //    dt.Seal();
        //    return dt;
        //}

        //private DataTemplate CreateCellTemplate(GridViewBoundColumnBase column)
        //{
        //    FrameworkElementFactory fe = new FrameworkElementFactory(typeof(TextBlock));
        //    fe.SetValue(TextBlock.ForegroundProperty, new SolidColorBrush(Colors.Blue));
        //    fe.SetBinding(TextBox.DataContextProperty, new Binding() { Converter = new ItemConverter(), ConverterParameter = column });
        //    fe.SetBinding(TextBlock.TextProperty, new Binding("Value"));
        //    DataTemplate dt = new DataTemplate();
        //    dt.VisualTree = fe;
        //    dt.Seal();
        //    return dt;
        //}
    }
}
