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

孤街浪徒 提交于 2019-12-12 00:36:35

问题


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:


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



来源:https://stackoverflow.com/questions/10502960/how-can-i-know-the-checked-unckecked-status-of-the-checkboxes-on-the-grid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!