I've constructed a DataGrid
by adding columns programatically using the following snippet:
var check = new FrameworkElementFactory(typeof(CheckBox), "chkBxDetail");
dgDetalle.Columns.Add(new DataGridTemplateColumn() { CellTemplate =
new DataTemplate() { VisualTree = check } });
for (int i = 0; i < 4; i++)
{
DataGridTextColumn textColumn = new DataGridTextColumn();
textColumn.Binding = new Binding(string.Format("[{0}]", i));
dgDetalle.Columns.Add(textColumn);
}
How can I know the checked/unckecked status of the checkboxes on the grid?
UPDATE
I can't use binding
Finally I got it...
I created the DataGrid
using this snippet:
var check = new FrameworkElementFactory(typeof(CheckBox));
dgDetalle.Columns.Add(new DataGridTemplateColumn()
{
CellTemplate = new DataTemplate() { VisualTree = check }
});
for (int i = 0; i < 4; i++)
{
DataGridTextColumn textColumn = new DataGridTextColumn();
textColumn.Binding = new Binding(string.Format("[{0}]", i));
dgDetalle.Columns.Add(textColumn);
}
Then, I made a snippet to show data from selected items in a MessageBox
:
string testValues = "";
for (int i = 0; i < dgDetalle.Items.Count; i++)
{
DataGridRow row = (DataGridRow)dgDetalle.ItemContainerGenerator.ContainerFromIndex(i);
FrameworkElement cellContent = dgDetalle.Columns[0].GetCellContent(row);
CheckBox checkBox = VisualTreeHelper.GetChild(cellContent, 0) as CheckBox;
if (checkBox != null && (checkBox.IsChecked ?? false))
{
List<string> item = (List<string>)dgDetalle.Items[i];
foreach (var t in item)
{
testValues += t;
}
}
}
MessageBox.Show(testValues);
To summarize:
- Get the row using
ItemContainerGenerator
- Get the specific column from the
DataGrid
and take it as a generic presentation object (FrameworkElement
)
- Get the content using
VisualTreeHelper
. Notice that I got the CheckBox
I've created on the first snippet
- Process the selected item
Hope it helps anyone...!