开发者

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)
    );
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜