【问题标题】:dynamically removing columns from grid in wpf在wpf中从网格中动态删除列
【发布时间】:2012-11-19 03:41:43
【问题描述】:

我有一个数字为 1 到 10 的组合框,根据用户的选择,我的表单上应该显示许多用户控件。第一次加载表单时,组合框的值为 1,并且只有一个用户控件 petdetails在网格中(只有一行,并且在进行更改时添加了额外的列)。我的程序在这种情况下工作正常,但是一旦用户添加了更高的值并由于某种原因减少了列,但最后一列中的控件重叠。(例如:用户选择了 6 个,添加了 6 个控件并且一次他将组合框中的值更改为 3,只剩下 3 列,但在第三列中,我可以看到用户控件 5,6 重叠)。我在这里粘贴我的代码,任何帮助将不胜感激。

private void cmbNoOfPets_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

        int i = Convert.ToInt32(((System.Windows.Controls.ContentControl)(cmbNoOfPets.SelectedValue)).Content);
        int grdCols=Convert.ToInt32(grdPetDetails .ColumnDefinitions .Count.ToString ()); 
        // check if the number of pets is more than the existing number in the grid if more start with adding at the next column
        // if less start from the last decreasing till the number of columns required
            if (i > grdCols)
            for (int j = grdCols+1 ; j <= i; j++)
            {

                ColumnDefinition c = new ColumnDefinition();
                c.Width = new GridLength(370, GridUnitType.Pixel);
                grdPetDetails.ColumnDefinitions.Add  (c);
                PetDetails petdetails = new PetDetails();
                petdetails.Name = "petDetails" + j ;
                string str="Pet Number " + j + ":";
                petdetails.lblPetNumber.Content = str;
                Grid.SetRow(petdetails, 1);
                Grid.SetColumn(petdetails, j - 1);
                grdPetDetails.Children.Add(petdetails);

           }
            else if (i < grdCols)

                for (int j = grdCols; j > i; j--)
                {

                    PetDetails petdetails = new PetDetails();
                    petdetails.Name = "petDetails" + j;
                    grdPetDetails.Children.Remove(petdetails);
                    grdPetDetails.ColumnDefinitions.RemoveAt(j - 1);


                } 

     }

我先删除控件,然后删除列定义,但不明白为什么会这样。

提前致谢。

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    因此,重新表述问题/请求“当我更改组合框的 SelectedItem 时,我希望在应用程序的其他位置显示新的 SelectedIndex+1 数量的控件。”看起来很简单,只需将事件处理程序连接到 SelectionChanged,并在该事件处理程序中创建控件。 http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.selector.selectionchanged.aspx

    【讨论】:

    • 我宁愿说它是 selectedindex 内容中的控件数量,每个控件都作为新列添加到现有网格中。添加工作正常,但我在删除列时遇到问题被删除,但控件保留在与该列中的控件重叠的最后一个现有列中,尽管我在删除列的列定义之前删除了控件。
    猜你喜欢
    • 1970-01-01
    • 2018-07-19
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    相关资源
    最近更新 更多