Vazamento de memória no aplicativo WPF devido a DelegateCommand
Acabei de terminar os aplicativos de desktop escritos em WPF e c # usando o padrão MVVM. Neste aplicativo, usei a implementação do Comando Delegado para agrupar as propriedades ICommands expostas no meu ModelView. O problema é que esses DelegateCommands impedem que meu ModelView e View sejam coletados como lixo após o fechamento da exibição. Portanto, ele permanece lento até que eu encerre o aplicativo inteiro. Eu perfil o aplicativo, acho que é tudo uma questão de delegar o comando, mantendo a visualização do modelo na memória. Como posso evitar essa situação e isso está na natureza do padrão mvvm ou é sobre a minha implantação do padrão ?. Obrigado.
Edit: esta é uma parte pequena, mas completa, de como eu implemento o padrão MVVM
Primeiro: classe CommandDelegte
class DelegateCommand:ICommand
{
private Action<object> execute;
private Predicate<object> canExcute;
public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
{
throw new ArgumentNullException("execute");
}
this.execute = execute;
this.canExcute = canExecute;
}
public bool CanExecute(object parameter)
{
if (this.canExcute != null)
{
return canExcute(parameter);
}
return true;
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
this.execute(parameter);
}
}
Segundo: Classe ModelView
public class ViewModel:DependencyObject, INotifyPropertyChanged
{
private DelegateCommand printCommand;
public ICommand PrintCommand
{
get
{
if (printCommand == null)
{
printCommand = new DelegateCommand(Print, CanExecutePrint);
}
return printCommand;
}
}
void Print(object obj)
{
Console.WriteLine("Print Command");
}
bool CanExecutePrint(object obj)
{
return true;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnProeprtyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Terceiro: código de janela atrás
public MainWindow()
{
InitializeComponent();
base.DataContext = new ViewModel();
}
Quarto: Meu XAML
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.InputBindings>
<KeyBinding Key="P" Modifiers="Control" Command="{Binding Path=PrintCommand}"/>
</Window.InputBindings>
<StackPanel>
<Button Content="Print - Ctrl+P" Width="75" Height="75" Command="{Binding Path=PrintCommand}"/>
</StackPanel>