Thread safe adding of subitem to a ListView control
I'm trying to convert an old Windows Forms Application to a WPF application.
The following code no longer compiles under 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(sub开发者_如何学GoitemText);
}
}
Please help to convert this code.
Hopefully the following blog post will help you. In WPF you use 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)
);
}
精彩评论