1

I want to dynamically add a combobox or a level in a particular cell of 7th column in a datagrid in wpf. Now I have an array of i elements. i am using a for loop which iterates i time , and every time it is checked whether the ith number of the array is greater than 1 or not. if it is greater than 1 , then the corresponding rows which satisfy the array's value are found out , and at the 7th column of each row of the datagrid , a combobox is added.

If the array value is equal to 1 , a label is added instead.

A similar application I did in ASP.NEt as follows

    if (count[i] > 1)
     {
       DropDownList drp = new DropDownList();
       drp.DataSource = dsq.Tables[0];
       drp.DataTextField = "Application Name";
       drp.DataValueField = "Application Name";
       drp.DataBind();
     if (row.Cells[0].Text.ToString().Trim().Equals(dt.Rows[i][0].ToString().Trim()))
       {
         row.Cells[7].Controls.Add(drp);
       }

    }
     else
     {
      Label l = new Label();
      l.Text = dsq.Tables[0].Rows[0][0].ToString().Trim();

     row.Cells[7].Controls.Add(l);
      }

Kindly let me know how to implement similar logic in datagrid in WPF.

4

1 回答 1

0

是的,经过大量研究,我找到了答案。请看下面:

 for (int j = 0; j < dt2.Rows.Count; j++)
   {
   DataGridRow row =  
   DataGridRow)dgApplications.ItemContainerGenerator.ContainerFromIndex(j);
   DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
   DataGridCell cell0 = 
   (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(0);

   ComboBox cb = new ComboBox();
 foreach (DataRow row2 in dsq.Tables[0].Rows)
    {
      ComboBoxItem cbx = new ComboBoxItem();
      cbx.Content = row2["Application Name"];
     cb.Items.Add(cbx);
    }                            
  cell7.Content = cb;

//GetVisual函数

   public static T GetVisualChild<T>(Visual parent) where T : Visual
{
    T child = default(T);

    Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate()
    {
        int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < numVisuals; i++)
        {
            Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
            child = v as T;
            if (child == null)
            {
                child = GetVisualChild<T>(v);
            }
            if (child != null)
            {
                break;
            }
        }

    }
   );
于 2013-04-26T19:32:31.687 回答