首页 > 代码库 > WPF DataGrid动态绑定

WPF DataGrid动态绑定

 foreach (DataColumn column in dt.Columns)            {                DateTime t;                if (DateTime.TryParse(column.ColumnName, out t))//判断表头是否为时期格式                {                    DataGridTemplateColumn newTemCol = new DataGridTemplateColumn();                    newTemCol.Header = column.ColumnName;                    DataTemplate dataTemplate = new DataTemplate();                    FrameworkElementFactory tbContent = new FrameworkElementFactory(typeof(TextBlock));                    // 设置内容                    tbContent.SetValue(TextBlock.TextProperty, new Binding(column.ColumnName));                    // 文字颜色                    tbContent.SetValue(TextBlock.ForegroundProperty, Brushes.Black);                    //如果是小于今天的日期,背景颜色全为灰                    if ((DateTime.Parse(column.ColumnName)) <= DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd")))                    {                        // 背景颜色                        tbContent.SetValue(TextBlock.BackgroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString("#808080")));                    }                    else                    {                        // 背景颜色                        Binding bindBackColor = new Binding(column.ColumnName);                        bindBackColor.Converter = new NowTimeBackGroundColor();                        bindBackColor.ConverterParameter = column.ColumnName;                        tbContent.SetValue(TextBlock.BackgroundProperty, bindBackColor);                    }                    // 单元格长度,用浮点数。                    tbContent.SetValue(TextBlock.WidthProperty, 80.0);                    dataTemplate.VisualTree = tbContent;                    newTemCol.CellTemplate = dataTemplate;                    dataGrid1.Columns.Add(newTemCol);                }                else                {                    DataGridTextColumn newCol = new DataGridTextColumn();                    newCol.Header = column.ColumnName;                    newCol.Binding = new Binding(column.ColumnName);                    dataGrid1.Columns.Add(newCol);                }            }            dataGrid1.ItemsSource = dt.DefaultView;