我有一个数字为 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);
}
}
我先删除控件,然后删除列定义,但后来不明白为什么会这样。
提前致谢。
最佳答案
因此,重新表述问题/请求“当我更改组合框的 SelectedItem 时,我希望新的 SelectedIndex+1 数量的控件显示在应用程序的其他位置。”看起来很简单,只需将事件处理程序连接到 SelectionChanged,并在该事件处理程序中创建控件。 http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.selector.selectionchanged.aspx
关于c# - 从 wpf 中的网格动态删除列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13435854/