我剛剛完成使用MVVM模式編寫WPF和c#的桌面應用程序。在這個應用程序中,我使用委託命令實現來包裝我的ModelView中公開的ICommands屬性。問題是這些DelegateCommands阻止我的ModelView和View在關閉視圖後被垃圾回收。所以它一直在讀書,直到我終止整個申請。我剖析了應用程序,我發現這完全是關於將modelview保存在內存中的delegatecommand。 我怎麼能避免這種情況,這是mvvm模式的性質,還是它關於我的模式植入?謝謝。由於DelegateCommand WPF應用程序中的內存泄漏
編輯:這是我如何實現MVVM模式
首先小而全部分: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);
}
}
二:模型視圖類
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));
}
}
}
三:窗口後面的代碼
public MainWindow()
{
InitializeComponent();
base.DataContext = new ViewModel();
}
第四:我的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>
你應該真的使用'Func