<p> <ItemsControl Grid.ColumnSpan="3" ItemsSource="{Binding MyItemsSource}" ItemTemplate="{StaticResource MyDataTemplate}" /></p>
<p> </p>
<p>ItemsControl has MyDataTemplate:</p>
<p> </p>
<p><DataTemplate x:Key="DayShiftViewModelDataTemplate"></p>
<p> <Grid Background="Red"></p>
<p> <TextBlock Text="FooText"/> </p>
<p> <controlsInputToolkit:ContextMenuService.ContextMenu></p>
<p> <controlsInputToolkit:ContextMenu ></p>
<p> <controlsInputToolkit:MenuItem UseLayoutRounding="False" Header="asdfsdf" Command="{Binding AddNewShiftCommand}"/></p>
<p> </controlsInputToolkit:ContextMenu></p>
<p> </controlsInputToolkit:ContextMenuService.ContextMenu></p>
<p> </Grid> </p>
<p> </DataTemplate></p>
<p> </p>
<p>When I clear the collection of ItemsSource and add new elements , my application starts to slow.</p>
<p>If I delete Context Menu from DataTemplate, application works well.</p>
Comments: ** Comment from web user: apudale **
We can solve this issue without modifying ToolKit.
Create a class which inherits from ContextMenu and implement IDisposable interface.
The mousemove eventhandler is not detached in ContextMenu and is measure cause of memory leak.
In Dispose remove event handler as shown in following code.
MethodInfo infos = typeof(ContextMenu).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).Where(a => a.Name.Equals("HandleRootVisualMouseMove")).FirstOrDefault();
Delegate handler = Delegate.CreateDelegate(typeof(MouseEventHandler), this , infos);
EventInfo info = Application.Current.RootVisual.GetType().GetEvent("MouseMove");
info.RemoveEventHandler(Application.Current.RootVisual, handler);
In this way you can remove memory leaks from any class without modification in origional class.