保留控件';s能见度良好
本文关键字:能见度 控件 保留 | 更新日期: 2023-09-27 18:19:58
这对你们中的一些人来说可能很容易。
我有一个文本框和一个列表框。ListBox为TextBox提供选项,并在双击事件中将所选项目的文本复制到TextBox。只有当TextBox触发Enter事件时,ListBox才可见。我不想讨论我选择这种控制组合的原因。
我希望ListBox在Form中的任何其他控件获得焦点时消失。因此,我捕获了TextBox的Leave事件并调用ListBox.Visible = fale
。问题是,当我单击ListBox选择所提供的选项时,TextBox也会失去焦点,从而阻止我选择该选项。我应该使用什么事件组合来保留ListBox以选择选项,但在其他控件获得焦点时将其隐藏?
在Leave
方法中,您可以在更改Visibility
:之前检查ListBox
是否为焦点控件
private void myTextBox_Leave(object sender, EventArgs e)
{
if (!myListBox.Focused)
{
myListBox.Visible = false;
}
}
此示例将为您提供所需的结果:
public Form1()
{
InitializeComponent();
textBox1.LostFocus += new EventHandler(textBox1_LostFocus);
textBox1.GotFocus += new EventHandler(textBox1_GotFocus);
}
void textBox1_GotFocus(object sender, EventArgs e)
{
listBox1.Visible = true;
}
void textBox1_LostFocus(object sender, EventArgs e)
{
if(!listBox1.Focused)
listBox1.Visible = false;
}
private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
textBox1.Text = listBox1.SelectedItem.ToString();
}
private void Form1_Shown(object sender, EventArgs e)
{
//if your textbox as focus when the form shows
//this is the place to switch focus to another control
listBox1.Visible = false;
}