你好!在 MVVM Light Toolkit 中使用交互触发器时,我发现内存泄漏。我使用这个 xaml
<UserControl x:Class="MemoryLeakTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ignore="http://www.ignore.com"
mc:Ignorable="d ignore"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:mvvm="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.SL5"
x:Name="control"
DataContext="{Binding Main, Source={StaticResource Locator}}">
<Grid x:Name="LayoutRoot">
<ItemsControl ItemsSource="{Binding LeakObjects}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Width="300" BorderThickness="6" BorderBrush="BlueViolet" CornerRadius="3">
<Grid Background="{Binding ColorBrush}" >
<StackPanel>
<Button Command="{Binding ElementName=control, Path=DataContext.Command}" Width="100" Height="40" Content="Tryck!">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<mvvm:EventToCommand Command="{Binding ElementName=control, Path=DataContext.Command}" CommandParameter="{Binding}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
<TextBlock Text="{Binding Text}"/>
</StackPanel>
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
然后我重新绑定列表 LeakObjects 以便它创建新项目。像按钮和文本块这样的旧项目 (xaml) 仍在内存中,不会被 GC。
如果我写
<Button Command="{Binding ElementName=control, Path=DataContext.Command}" Width="100" Height="40" Content="Press!"/>
并使用按钮命令参数没有内存泄漏,但如果我使用
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<mvvm:EventToCommand Command="{Binding ElementName=control, Path=DataContext.Command}" CommandParameter="{Binding}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
有重大泄漏。
问题是网格等上没有命令参数。
链接中的项目有这个非常简单的项目来演示问题。
有没有办法避免内存泄漏?也许我用错了。
找到解决此问题的方法至关重要,因为这种内存泄漏遍布我们的应用程序。