gpt4 book ai didi

c# - 防止选择 Winforms ListBox 中的某些项目

转载 作者:太空宇宙 更新时间:2023-11-03 12:56:31 26 4
gpt4 key购买 nike

我见过一些类似的问题,但它们似乎是针对 WPF 的(我不熟悉,解决方案似乎不适用于我)。我有一个 OwnerDrawFixed 列表框(好吧,实际上是 2 个),如果添加的项目是 "",我用它来绘制水平分隔符项目。我想要的是在点击时完全跳过这些(我在点击拖动选择它的项目时遇到了麻烦)或通过向上/向下箭头键选择。这是我的 DrawItem 事件:

private void ListBox_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index < 0)
return;

e.DrawBackground();
e.Graphics.DrawString((sender as ListBox).Items[e.Index].ToString(), (sender as ListBox).Font, new SolidBrush(e.ForeColor), e.Bounds);

//Draw as a separator if there is no text
if (string.IsNullOrWhiteSpace((sender as ListBox).Items[e.Index].ToString()))
{
e.Graphics.DrawLine(new Pen(Brushes.DarkGray), new Point(e.Bounds.X + 5, e.Bounds.Y + 7), new Point(e.Bounds.X + e.Bounds.Width - 5, e.Bounds.Y + 7));
}
//Doesn't appear to do anything e.DrawBackground isn't..?
//e.DrawFocusRectangle();
}

我已经尝试了 MouseUp、MouseDown 和 SelectedIndexChanged 事件的组合,或者完全清除选择(由于明显的原因不利于箭头导航)或存储先前选择的索引、确定方向并选择下一个值(如果项目不靠近,有时点击不直观)。
我也试过 myListBox.SelectionMode = SelectionMode.None;,但出于某种原因(也许是我的绘图事件?)它只是突出显示我选择的每个项目(没有取消选择它们)。

如果我试图禁止选择项目为空字符串的项目,我是否遗漏了什么?

最佳答案

这是一个适合我的简单解决方案。我刚刚将这一事件添加到您发布的代码中:

int lastIndex = 0;
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string s = listBox1.SelectedItem.ToString();
int newIndex = listBox1.SelectedIndex;
if (s == "" )
{
if (newIndex > lastIndex && newIndex < listBox1.Items.Count)
{
listBox1.SelectedIndex++;
}
else if (newIndex < lastIndex && newIndex > 0)
{
listBox1.SelectedIndex--;
}
}
else lastIndex = newIndex;
}

关于c# - 防止选择 Winforms ListBox 中的某些项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33653832/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com