通过另一个线程显示/隐藏标签 [英] Showing/hiding label by another thread
本文介绍了通过另一个线程显示/隐藏标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的代码中无法进行某项操作,因此我想询问是否有人可以帮助我.到目前为止,我已经知道了:
Someting doesn't work in my code so I wanted to ask if someone can help me. I have this so far:
private void searchList_TextChanged(object sender, EventArgs e)
{
Thread th = new Thread(new ThreadStart(setLabel));
th.IsBackground = true;
th.Start();
//some code that needs time
if (searchBox.Text == String.Empty)
{
listViewType.Items.Clear();
fillListView();
}
else
{
listViewType.Items.Clear();
var matchings = stringTypes.FindAll(delegate(string s) { return s.StartsWith(searchBox.Text); });
for (int i = 0; i < matchings.Count; i++)
{
ListViewItem storeMatched = new ListViewItem(matchings[i]);
storeMatched.SubItems.Add(matchings[i]);
listViewType.Items.Add(storeMatched);
}
th.Abort();
searchLabel.Visible = false;
}
private void setLabel()
{
MethodInvoker set = () => searchLabel.Visible = true;
searchLabel.BeginInvoke(set);
}
所以searchLabel是我要显示/隐藏的标签.我在这里尝试在操作开始之前显示标签,并在操作完成后将其隐藏.代码执行后(或一些需要时间的代码)以某种方式显示出来,然后保持可见状态.如何正确编码?
So searchLabel is a label that I want to show/hide. I tried here to show the label before the operation begins and hide it after it finished. Somehow it gets shown AFTER the code was executed (//some code that needs time) and then stays visible. How to code that correctly?
推荐答案
private void searchList_TextChanged(object sender, EventArgs e)
{
searchLabel.Visible = false;
backgroundWorker.RunWorkerAsync();
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
//some code that needs time
Thread.Sleep(1000);
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
SetLabelVisible(true);
}
private delegate void SetLabelVisibleDelegate(bool status);
private void SetLabelVisible(bool status)
{
if (searchLabel.InvokeRequired)
searchLabel.Invoke(new SetLabelVisibleDelegate(SetLabelVisible), status);
else
searchLabel.Visible = status;
}
这篇关于通过另一个线程显示/隐藏标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文