[英]ListBox topIndex doesn't work
我尝试使用以下代码将列表框的 selectedIndex 放在显示列表的顶部:
private void textBox1_TextChanged(object sender, EventArgs e)
{
sourceListBox.SelectionMode = SelectionMode.One;
if (textBox1.Text != string.Empty)
{
int index = sourceListBox.FindString(textBox1.Text);
if (index != -1 && sourceListBox.SelectedIndex != index)
{
sourceListBox.ClearSelected();
sourceListBox.SetSelected(index, true);
sourceListBox.TopIndex = sourceListBox.SelectedIndex;
}
}
else
{
sourceListBox.ClearSelected();
}
sourceListBox.SelectionMode = SelectionMode.MultiExtended;
}
但是选定的索引卡在列表框的底部:
这是唯一改变列表框行为的代码部分。 我该如何解决?
看起来像对sourceListBox.SelectionMode = SelectionMode.MultiExtended;
的调用sourceListBox.SelectionMode = SelectionMode.MultiExtended;
正在重置TopIndex
。 在该调用之后设置TopIndex
将起作用:
private void textBox1_TextChanged(object sender, EventArgs e)
{
int topIndex = sourceListBox.TopIndex;
sourceListBox.SelectionMode = SelectionMode.One;
if (textBox1.Text != string.Empty)
{
int index = sourceListBox.FindString(textBox1.Text);
if (index != -1 && sourceListBox.SelectedIndex != index)
{
sourceListBox.ClearSelected();
sourceListBox.SetSelected(index, true);
topIndex = sourceListBox.SelectedIndex;
}
}
else
{
sourceListBox.ClearSelected();
}
sourceListBox.SelectionMode = SelectionMode.MultiExtended;
sourceListBox.TopIndex = topIndex;
}
取消对当前的SelectedIndex的检查,并且即使当前的SelectedIndex等于FindString的结果,设置TopIndex的代码也将始终执行
private void textBox1_TextChanged(object sender, EventArgs e)
{
.....
int index = sourceListBox.FindString(textBox1.Text);
if (index != -1)
{
sourceListBox.ClearSelected();
sourceListBox.SetSelected(index, true);
sourceListBox.TopIndex = sourceListBox.SelectedIndex;
}
....
}
更改
sourceListBox.TopIndex = sourceListBox.SelectedIndex;
至
sourceListBox.TopIndex = index;
到 winforms 列表框
SendMessage(listBox.Handle,LB_SETTOPINDEX, 0, 0);
将使最顶层的项目可见,保证,而无需更改其选择 state,这在刚刚启动应用程序并反序列化以加载列表框时可能是一个很好的接触。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.