2015-09-07 96 views
0

我很难创建一个类,我可以使用ListBox来记录事件。 我知道我有很多关于我和谷歌的问题的文章,但是我没有写出来。所以我问了一些帮助这里:使用Listbox UI事件日志记录

我有三类:

1:WinForm的 - 我在哪里列表框放置。从这里我通过我的列表框中的FileEnumeratorClass()构造函数。

2:FileEnumeratorClass - 收到列表框,然后将它传递给记录器类。

class FileEnumeratorClass { 
    UILogger logger; 
    /// <summary> 
    ///  ctor 
    /// </summary> 
    public FileEnumeratorClass (ListBox lbLog) 
    { 
     logger = new UILogger(lbLog); 
    } 

    /// <summary> 
    ///  Figures out what has changed between the src and destination 
    ///  What is currently implemented does not work......the solution is to compare SRC and DESTINATION for the first time. 
    ///  And verify with end user. 
    /// </summary> 
    public List<FileDetails> IdentifyChanges() 
    { 
     logger.AddToLog("Change detection initiated..."); 
     //Deletes any existing cached package. Assuming it is in incosistent form 
     logger.AddToLog("Cleaning up any cached local package."); 
     DeleteLocalPackage(); 
    } 
} 

3:UILogger

public class UILogger 
{ 
    public UILogger(ListBox lb) 
    { 
     lbLog = lb; 
    } 
    // This delegate enables asynchronous calls for setting 
    // the text property on a control. 
    delegate void AddToLogCallback(string text); 

    public void AddToLog(string message) 
    { 
     // InvokeRequired required compares the thread ID of the 
     // calling thread to the thread ID of the creating thread. 
     // If these threads are different, it returns true. 
     if (lbLog.InvokeRequired) 
     { 
      var d = new AddToLogCallback(AddToLog); 
      lbLog.Invoke(d, new object[] { message }); 
     } 
     else 
     { 
      // add this line at the top of the log 
      lbLog.Items.Insert(0, message); 

     } 

     // keep only a few lines in the log 
     while (lbLog.Items.Count > 1000) 
     { 
      lbLog.Items.RemoveAt(lbLog.Items.Count - 1); 
     } 
    }  
} 

但上面的代码不能按预期工作。线程完成时全部显示。我需要的是按照在FileEnumeratorClass - > IdentifyChanges()中写入/调用的顺序调用方法AddToLog()

+0

直到操作完成后,主线程会做什么? – taffer

+0

老兄,忘了winforms,看看[我的例子](http://stackoverflow.com/a/16745054/643085)如何以闪电般的速度,多线程支持和更丰富的用户界面。 –

回答

-1

无论何时您想要listbox更新其内容以强制listbox重新绘制自己,您都需要调用Control.Invalidate()方法。 请注意,这些控件是线程安全的,这意味着任何异步或子线程都不能更新任何UI控件。对UI线程使用适当的回调,并让UI线程更新控件。

public List<FileDetails> IdentifyChanges() 
{ 
    logger.AddToLog("Change detection initiated..."); 
    //Deletes any existing cached package. Assuming it is in incosistent form 
    logger.AddToLog("Cleaning up any cached local package."); 

    //Invalidate the control to redraw. 
    logger.Invalidate(); 

    DeleteLocalPackage(); 
} 
+0

不,添加元素会使控件失效。问题在于操作完成之前,控件没有时间刷新自己。强制刷新会更新控件;但是,应该避免。 – taffer