2011-09-24 59 views
0

我想將舊的Windows窗體應用程序轉換爲WPF應用程序。線程安全地添加子項到一個ListView控件

下面的代碼不再在C#.NET 4.0編譯:

// Thread safe adding of subitem to ListView control 
private delegate void AddSubItemCallback(
    ListView control, 
    int item, 
    string subitemText 
); 

private void AddSubItem(
    ListView control, 
    int item, 
    string subitemText 
) { 
    if (control.InvokeRequired) { 
    var d = new AddSubItemCallback(AddSubItem); 
    control.Invoke(d, new object[] { control, item, subitemText }); 
    } else { 
    control.Items[item].SubItems.Add(subitemText); 
    } 
} 

請幫忙把這段代碼轉換。

+0

使用Dispatcher.CheckAccess和Dispatcher.Invoke代替。 –

回答

0

希望following blog post會幫助你。在WPF使用Dispatcher.CheckAccess/Dispatcher.Invoke

if (control.Dispatcher.CheckAccess()) 
{ 
    // You are on the GUI thread => you can access and modify GUI controls directly 
    control.Items[item].SubItems.Add(subitemText); 
} 
else 
{ 
    // You are not on the GUI thread => dispatch 
    AddSubItemCallback d = ... 
    control.Dispatcher.Invoke(
     DispatcherPriority.Normal, 
     new AddSubItemCallback(AddSubItem) 
    ); 
} 
+0

代碼:control.Items [item] .SubItems.Add(subitemText);不再在.NET 4.0 WPF下編譯。我得到「無法解析」子項目「。 – CBrauer