WPF Datagrid: Checkbox and Button stackpanel

Christopher 1 Reputation point


I coded in xaml.cs my datagrid with a single column of checkbox and button using factory and stackpanel. Right now I want to detect what column and row they are and if the checkbox ischecked = true. My column headers on datagrid are dynamic based on the dates range they chose

This is my sample code:

 int extra = 1;
                while (startDate < endDate.AddDays(1))

                    string combo1 = "combo" + extra;

                    var col2 = new DataGridTemplateColumn();
                    string colname = startDate.ToShortDateString() + " [" + Utils.ToDateTime(startDate).ToString("ddd") + "]";
                    col2.Header = colname;
                    var template2 = new DataTemplate();
                    var sp = new FrameworkElementFactory(typeof(StackPanel));
                    sp.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
                    var buttonfactoy = new FrameworkElementFactory(typeof(Button));

                    col2.CellTemplate = template2;
                    dtDailyShift.Columns.Add(startDate.ToShortDateString(), typeof(string));

                    buttonfactoy.SetValue(Button.HeightProperty, 35.0);
                    buttonfactoy.SetValue(Button.ContentProperty, "CLICK FOR SHIFT");
                    buttonfactoy.SetValue(Button.MarginProperty, new Thickness(5));
                    buttonfactoy.SetResourceReference(Button.StyleProperty, "ButtonPrimary");
                    buttonfactoy.SetResourceReference(Button.HorizontalContentAlignmentProperty, HorizontalAlignment.Center);
                    // A column named 'System.Windows.Controls.DataGridTemplateColumn' already belongs to this DataTable.'
                    buttonfactoy.AddHandler(Button.ClickEvent, new RoutedEventHandler((o, f) => HandleColumnButtonClick(o, f)));


                    template2.VisualTree = sp;
                    startDate = startDate.AddDays(1);

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,710 questions
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
789 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Peter Fleischer (former MVP) 19,316 Reputation points

    Hi Christopher,
    instead of "buttonfactoy.AddHandler(Button.ClickEvent, ..." use Command property with ICommand class and CommandParameter bindet to current data item. In Execute method you get as state the item of clicked row.

    0 comments No comments