What is your storeColumns
? Is it type List<DataGridTemplateColumn>
? If it is, how do you add data to storeColumns
? If you do not give data to it first, you may meet some error. I tested your code with some updates and used storeColumns
as DataGridTemplateColumn storeColumns = new DataGridTemplateColumn();
, then can implement background.
public void testc()
{
List<ScheduleUnit> _myWorkDataSource = new List<ScheduleUnit>()
{
new ScheduleUnit(){EmployeeID=001,Date=System.DateTime.Now,DisplayText="Text001",StoreID=0001,DisplayColor=Color.FromRgb(255,0,0)},
new ScheduleUnit(){EmployeeID=002,Date=System.DateTime.Now,DisplayText="Text002",StoreID=0002,DisplayColor=Color.FromRgb(255,255,0)}
};
dgSchedule.ItemsSource = _myWorkDataSource;
//List<DataGridTemplateColumn> storeColumns = new List<DataGridTemplateColumn>();
DataGridTemplateColumn storeColumns = new DataGridTemplateColumn();
// create a textblock
FrameworkElementFactory textFactory = new FrameworkElementFactory(typeof(TextBlock));
textFactory.SetBinding(TextBlock.TextProperty, new Binding("EmployeeID"));
//textFactory.SetValue(HorizontalAlignmentProperty, HorizontalAlignment.Center);
DataTemplate textTemplate = new DataTemplate();
textTemplate.VisualTree = textFactory;
// Set the Templates to the Column
storeColumns.CellTemplate = textTemplate;
// prepare a style for the main cells
Style mainColsStyle = new Style(typeof(DataGridCell));
// define the background color
Setter bgColorSetter = new Setter();
bgColorSetter.Property = DataGridCell.BackgroundProperty;
SolidColorBrush bgColorBrush = new SolidColorBrush();
Binding bgColorBinding = new Binding("DisplayColor");
// => this causes the slow down and errors
BindingOperations.SetBinding(bgColorBrush, SolidColorBrush.ColorProperty, bgColorBinding);
bgColorSetter.Value = bgColorBrush;
mainColsStyle.Setters.Add(bgColorSetter);
storeColumns.CellStyle = mainColsStyle;
storeColumns.Header = "Mycustom column";
dgSchedule.Columns.Add(storeColumns);
}
The result picture is:
Did it do any help for your analysis? If it doesn't, please let me know and give me more info.
If the response is helpful, please click "Accept Answer" and upvote it.
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.