How can I know the checked/unckecked status of the

2019-09-06 15:45发布

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

1条回答
放我归山
2楼-- · 2019-09-06 16:45

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...!

查看更多
登录 后发表回答