2015-09-07 114 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