Ich habe gerade Desktop-Apps fertig geschrieben in WPF und C# mit MVVM-Muster. In dieser App habe ich die Delegate Command-Implementierung verwendet, um die ICommands-Eigenschaften zu umbrechen, die in meinem ModelView verfügbar sind. Das Problem ist, dass diese DelegateCommands verhindern, dass ModelView und View nach dem Schließen der Ansicht als Garbage Collected erfasst werden. Es bleibt also solange larking, bis ich die gesamte Anwendung beendet habe. Ich profiliere die Anwendung Ich finde, dass es alles über delegatecommand ist, der das modelview in Gedächtnis behält. Wie könnte ich diese Situation vermeiden und ist dies in der Natur der MVVM-Muster, oder es ist über meine Implantation des Musters ?. Vielen Dank.Speicherverlust in der WPF-App aufgrund von DelegateCommand
Edit: dies ist klein, aber komplette Teil, wie ich MVVM Muster
Erste Umsetzung: CommandDelegte Klasse
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);
}
}
Zweitens: Modelview Klasse
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));
}
}
}
Drittens: Fenster Code hinter
public MainWindow()
{
InitializeComponent();
base.DataContext = new ViewModel();
}
Forth: Meine 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>
Sie sollten wirklich 'Func