我正在制作一个扩展 CheckedListBox 的简单类,它只是在选中项目时在其右侧添加一个小文本框。我的问题是找到一种将盒子放在正确位置的好方法。
虽然我最初可以使用 Controls.Find() 和 ItemCheckEventArgs 索引来获取相关复选框的坐标,然后从那里移动到列的右边缘。然而,这没有用,通过 CheckedListBox 类的简要浏览似乎表明它实际上不包含任何 CheckBox 控件,而只是绘制它们的图像。
然后我想出了以下方法:
void CreateAmountBox(int index)
{
int itemsPerCol = Height/ItemHeight;
int x = GetColumn(index, itemsPerCol)*ColumnWidth - boxWidth;
int y = (index % itemsPerCol)*ItemHeight - offset;
System.Windows.Forms.TextBox NewAmountTextBox = new System.Windows.Forms.TextBox();
NewAmountTextBox.Location = new System.Drawing.Point(x, y);
NewAmountTextBox.Name = Items[index] + "Amount";
NewAmountTextBox.Size = new System.Drawing.Size(20, boxWidth);
Controls.Add(NewAmountTextBox);
}
其中 GetColumn(...) 返回给定索引的列(来自 CheckEventArgs)。这行得通,但感觉像是 hack,可读性不强。
我想到的另外两个想法:
1) 我可以在一开始就创建所有的文本框,然后简单地隐藏它们直到需要它们。然而,像这样的控件都是在程序的其余部分动态创建的,我不希望这些控件成为奇怪的异常(exception)。这也意味着需要为添加或删除项目的情况添加更多功能。
2) 我可以使用鼠标位置,如果通过键盘输入,这当然不起作用。我不希望它永远如此,但最好不要留下这种可能性。
通过一些谷歌搜索,我发现可能这样做的唯一其他方法是使用 ListBoxItem 和 TranslatePoint 方法,但我还没有让它工作,我不确定它是否可以用 CheckedListBox 代替列表框的。
那么,有没有一种简单的方法可以找到我不知道的已选中项目的 x 和 y?或者我是否仅限于简单地将上面的 x 和 y 声明提取到一个方法中并将其留在那里?
最佳答案
您可以只使用 GetItemRectangle 函数来完成:
void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
Rectangle r = checkedListBox1.GetItemRectangle(e.Index);
TextBox newAmountTextBox = new TextBox();
newAmountTextBox.Location = new Point(r.Left, r.Top);
//...
}
关于c# - 有没有一种简单的方法来获取选中列表框中特定项目的坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24539062/