How can I know the checked/unckecked status of the checkboxes on the grid?
Asked Answered
M

1

0

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

Mettlesome answered 8/5, 2012 at 16:55 Comment(4)
You bind a collection to the DataGrid and that boolean property is the status of the checkbox.Depositor
@Blam I'm not using binding because the grid does not have a fixed set of columns...Mettlesome
That should not stop you from binding but I have tried to help you before and your typical response is that won't work.Depositor
@Blam I've not said it will not work. I simply can't because I'm doing code mainteinance and the ItemsSource is set to a string[][], so to modify all the already written code could take more time than simply write the snippet to get the desired value.Mettlesome
M
0

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:

  1. Get the row using ItemContainerGenerator
  2. Get the specific column from the DataGrid and take it as a generic presentation object (FrameworkElement)
  3. Get the content using VisualTreeHelper. Notice that I got the CheckBox I've created on the first snippet
  4. Process the selected item

Hope it helps anyone...!

Mettlesome answered 9/5, 2012 at 14:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.