图解大纲
可观察对象的实现
通过事件来通知所有的观察者。
namespace MVVM.Framework
{
// 实现观察者主题的通知
public class BaseObservableObject : INotifyPropertyChanged
{
// 事件
public event PropertyChangedEventHandler PropertyChanged;
// 标准的触发事件的方法
protected void OnPropertyChanged(string propertyName)
{
// 如果没有注册,会是 null
if (PropertyChanged != null)
{
var e = new PropertyChangedEventArgs(propertyName);
PropertyChanged(this, e);
}
}
}
}
命令的实现
namespace System.Windows.Input
{
// 摘要:
// 定义一个命令
[TypeConverter("System.Windows.Input.CommandConverter, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, Custom=null")]
[TypeForwardedFrom("PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")]
[ValueSerializer("System.Windows.Input.CommandValueSerializer, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, Custom=null")]
public interface ICommand
{
// 摘要:
// 当出现影响是否应执行该命令的更改时发生。
event EventHandler CanExecuteChanged;
// 摘要:
// 定义用于确定此命令是否可以在其当前状态下执行的方法。
//
// 参数:
// parameter:
// 此命令使用的数据。 如果此命令不需要传递数据,则该对象可以设置为 null。
//
// 返回结果:
// 如果可以执行此命令,则为 true;否则为 false。
bool CanExecute(object parameter);
//
// 摘要:
// 定义在调用此命令时调用的方法。
//
// 参数:
// parameter:
// 此命令使用的数据。 如果此命令不需要传递数据,则该对象可以设置为 null。
void Execute(object parameter);
}
}
namespace MVVM.Framework
{
/// <summary>
/// 实现命令支持
/// </summary>
public class DelegateCommand : ICommand
{
// 是否可执行的条件
private readonly Predicate<Object> canExecuteMethod;
// 实际执行的操作, 表示有一个对象作为参数的方法
private readonly Action<Object> executeActionMethod;
// 构造函数
// 创建命令对象的时候,提供实际执行方法的委托
// 判断是否启用的委托
public DelegateCommand(
Predicate<Object> canExecute,
Action<object> executeAction
)
{
canExecuteMethod = canExecute;
executeActionMethod = executeAction;
}
#region ICommand Members
public event EventHandler CanExecuteChanged;
// 检查是否可以执行
public bool CanExecute(object parameter)
{
var handlers = canExecuteMethod;
if (handlers != null)
{
return handlers(parameter);
}
return true;
}
// 执行操作
public void Execute(object parameter)
{
// 检查是否提供了实际的方法委托
var handlers = executeActionMethod;
if (handlers != null)
{
handlers(parameter);
}
// 执行之后,更新是否可以执行的状态
UpdateCanExecuteState();
}
#endregion
public void UpdateCanExecuteState()
{
var handlers = CanExecuteChanged;
if (handlers != null)
{
handlers(this, new EventArgs());
}
}
}
}
下面为代码实现
添加链接描述
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/51769.html