Tôi vừa hoàn thành các ứng dụng dành cho máy tính để bàn được viết bằng WPF và C# sử dụng mẫu MVVM. Trong ứng dụng này, tôi đã sử dụng thực thi Lệnh Delegate để bọc các thuộc tính ICommands được hiển thị trong ModelView của tôi. Vấn đề là các DelegateCommands này ngăn cản ModelView và View của tôi khỏi bị thu gom rác sau khi đóng khung nhìn. Vì vậy, nó vẫn larking cho đến khi tôi chấm dứt toàn bộ ứng dụng. Tôi hồ sơ ứng dụng tôi tìm thấy tất cả về delegatecommand rằng giữ modelview trong bộ nhớ. Làm cách nào để tránh tình trạng này và điều này có tính chất mvvm, hay là do việc cấy ghép mô hình của tôi ?. Cảm ơn.Rò rỉ bộ nhớ trong ứng dụng WPF do DelegateCommand
Edit: đây là phần nhỏ nhưng đầy đủ về cách tôi thực hiện MVVM pattern
Đầu tiên: lớp 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);
}
}
Thứ hai: ModelView Lớp
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));
}
}
}
Thứ ba: Mã Window đằng sau
public MainWindow()
{
InitializeComponent();
base.DataContext = new ViewModel();
}
Forth: XAML My
<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>
Bạn thực sự nên sử dụng 'Func