这两段代码在功能上是等效的,但它们使用了不同的 `RelayCommand` 实现。第一段代码中,`RelayCommand` 是自定义实现的,而第二段代码中,`RelayCommand` 是使用 `GalaSoft.MvvmLight.Command` 库中的实现。
以下是两段代码的完整版本,以便更好地理解它们的等效性:
### 第一段代码
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
namespace Zhaoxi.DigitaPlatform.Models
{
public class ThumbModel
{
public string Header { get; set; }
public List<ThumbItemModel> Children { get; set; } = new List<ThumbItemModel>();
}
public class ThumbItemModel
{
public string Icon { get; set; }
public string TargetType { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public ICommand ThumbCommand { get; set; }
public ThumbItemModel()
{
ThumbCommand = new RelayCommand<object>(DoThunmCommand);
}
private void DoThunmCommand(object obj)
{
DragDrop.DoDragDrop(obj as DependencyObject, this, DragDropEffects.Copy);
}
}
public class RelayCommand<T> : ICommand
{
private readonly Action<T> _execute;
private readonly Predicate<T> _canExecute;
public RelayCommand(Action<T> execute) : this(execute, null)
{
}
public RelayCommand(Action<T> execute, Predicate<T> canExecute)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute((T)parameter);
}
public void Execute(object parameter)
{
_execute((T)parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}
}
```
### 第二段代码
```csharp
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
namespace Zhaoxi.DigitaPlatform.Models
{
public class ThumbModel
{
public string Header { get; set; }
public List<ThumbItemModel> Children { get; set; } = new List<ThumbItemModel>();
}
public class ThumbItemModel
{
public string Icon { get; set; }
public string TargetType { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public RelayCommand<object> ThumbCommand { get; set; }
public ThumbItemModel()
{
ThumbCommand = new RelayCommand<object>(DoThunmCommand);
}
private void DoThunmCommand(object obj)
{
DragDrop.DoDragDrop(obj as DependencyObject, this, DragDropEffects.Copy);
}
}
}
```
### 总结
- 两段代码都定义了 `ThumbModel` 和 `ThumbItemModel` 类。
- `ThumbItemModel` 类中都有一个 `ThumbCommand` 属性,用于处理拖放操作。
- 第一段代码中,`RelayCommand` 是自定义实现的,而第二段代码中,`RelayCommand` 是使用 `GalaSoft.MvvmLight.Command` 库中的实现。
因此,这两段代码在功能上是等效的,只是 `RelayCommand` 的实现方式不同。