在一个项目上工作我遇到了这样的问题:我创建自定义控件库WPF,我的类继承了网格类,我在那里添加行到行定义集合。有一种方法可以更改之间的行。当我想删除最后一行时更改行后,我得到一个异常" ArgumentOutOfRangeException"。我理解为什么我会得到这个例外。唯一的出路我看到如何解决这个问题 - 改变行,但没有替换索引。可以这样做吗?
一些代码(将它列为我自己的类):
public void AppendPanel()
{
var panel = new Panel(this);
var row = new RowDefinition
{
Height = new GridLength(ActualHeight * 0.2, GridUnitType.Star),
};
RowDefinitions.Add(row);
Children.Add(panel);
SetRow(panel, RowDefinitions.Count - 1);
}
private void SwapPanels(Panel currentPanel, Panel nextPanel, Int32 currentIndex, Int32 nextIndex)
{
SetRow(currentPanel, nextIndex);
SetRow(nextPanel, currentIndex);
var tmp = RowDefinitions[currentIndex].Height;
RowDefinitions[currentIndex].Height = RowDefinitions[nextIndex].Height;
RowDefinitions[nextIndex].Height = tmp;
}
public Boolean MovePanelUp(Panel panel, Int32 movePosition = 1)
{
var currentRowIndex = GetRow(panel);
var upperRowIndex = currentRowIndex - 1 * movePosition;
if (currentRowIndex == 0 || upperRowIndex < 0)
{
return false;
}
var upperPanel = Children.Cast<UIElement>()
.Where(x => GetRow(x) == upperRowIndex)
.OfType<Panel>()
.FirstOrDefault();
SwapPanels(panel, upperPanel, currentRowIndex, upperRowIndex);
return true;
}
public void RemovePanel(Panel panel)
{
var rowIndex = GetRow(panel);
Children.Remove(panel);
RowDefinitions.RemoveAt(rowIndex);
}