原文标题:Adventures in MVVM – Binding Commands to ANY Event
当我实现MVVM模式时,令我最为头疼一件事是需要给事件绑定命令。当我使用Prism框架时,我得到一个Button.Click的命令绑定,但是每一个其他的时间都需要单独的进行处理。做这些的时候,需要很多的容易出错的样板代码。在我过去的工作岗位上,我发表一些代码来减轻疼痛。然而,仍需要你针对每一个你想进行绑定的事件写一个新的行为和附加内容。
有一段时间了,我的想法只是直接绑定命令到时间。在这期间我遇到很多困难。例如,每一个事件处理都有一个同的事件参数类型。这需要所有的处理都是动态的。我仍然不能创建一个内置的命令绑定--我将确信对每一个单一控件绑定到超过1个的事件。因此我需要创建一个绑定的集合。创建结构体数据就是给自己创造麻烦---绑定仅工作在VisualTree的FrameWorkElements上。这需要我来写自己的绑定基于我的通用的行为。
以下是非常松散的基础下Chinch MVVM框架。我测试了这些代码在Silverlight和WPF,并且运行真的不错!
public class MainPageviewmodel : INotifyPropertyChanged { ... public ICommand MouseLeaveCommand { get; private set; } public ICommand MouseEnterCommand { get; private set; } public ICommand ClickCommand { get; private set; } ... }
我能绑定命令到一个控件的时间上,以一Button为例:
Button Content="Click Me"> <Behaviors:Events.Commands> <Behaviors:EventCommandCollection> <Behaviors:EventCommand CommandName="MouseEnterCommand" EventName="MouseEnter" /> <Behaviors:EventCommand CommandName="MouseLeaveCommand" EventName="MouseLeave" /> <Behaviors:EventCommand CommandName="ClickCommand" EventName="Click" /> </Behaviors:EventCommandCollection> </Behaviors:Events.Commands> </Button>
我不再需写任何的额外的代码,无论何时我想附加命令到我的事件上!下面是砂锅面代码的警告:
- the XAML requires the EventCommandCollection to be declared in the XAML. I struggled to figure out how to eliminate this but gave up. Someone smarter than me might be able to tell me what I am doing wrong.
- This code does not consider command properties. Every command assumes a null parameter. If you need parameters (like data context),then you’ll have to do something differently (either use the old-school mechanism or extend this code to handle some special event types).
- You don’t bind directly to the command. Instead,you declare the name of the command (Notice CommandName is not bound). The behavior binds for you using a primitive mechanism.
下面给出命令的行为,它可以完成所有的工作:
public class Events { private static readonly DependencyProperty EventBehaviorsProperty = DependencyProperty.Registerattached( "EventBehaviors",typeof(EventBehaviorCollection),typeof(Control),null); private static readonly DependencyProperty InternalDataContextProperty = DependencyProperty.Registerattached( "InternalDataContext",typeof(Object),new PropertyMetadata(null,DataContextChanged)); private static void DataContextChanged(DependencyObject dependencyObject,DependencyPropertyChangedEventArgs e) { var target = dependencyObject as Control; if (target == null) return; foreach (var behavior in GetorCreateBehavior(target)) behavior.Bind(); } public static readonly DependencyProperty CommandsProperty = DependencyProperty.Registerattached( "Commands",typeof(EventCommandCollection),typeof(Events),CommandsChanged)); public static EventCommandCollection GetCommands(DependencyObject dependencyObject) { return dependencyObject.GetValue(CommandsProperty) as EventCommandCollection; } public static void SetCommands(DependencyObject dependencyObject,EventCommandCollection eventCommands) { dependencyObject.SetValue(CommandsProperty,eventCommands); } private static void CommandsChanged(DependencyObject dependencyObject,DependencyPropertyChangedEventArgs e) { var target = dependencyObject as Control; if (target == null) return; var behaviors = GetorCreateBehavior(target); foreach (var eventCommand in e.NewValue as EventCommandCollection) { var behavior = new EventBehavior(target); behavior.Bind(eventCommand); behaviors.Add(behavior); } } private static EventBehaviorCollection GetorCreateBehavior(FrameworkElement target) { var behavior = target.GetValue(EventBehaviorsProperty) as EventBehaviorCollection; if (behavior == null) { behavior = new EventBehaviorCollection(); target.SetValue(EventBehaviorsProperty,behavior); target.SetBinding(InternalDataContextProperty,new Binding()); } return behavior; } } public class EventCommand { public string CommandName { get; set; } public string EventName { get; set; } } public class EventCommandCollection : List<EventCommand> { } public class EventBehavior : CommandBehaviorBase<Control> { private EventCommand _bindingInfo; public EventBehavior(Control control) : base(control) { } public void Bind(EventCommand bindingInfo) { ValidateBindingInfo(bindingInfo); _bindingInfo = bindingInfo; Bind(); } private void ValidateBindingInfo(EventCommand bindingInfo) { if(bindingInfo == null) throw new ArgumentException("bindingInfo"); if (string.IsNullOrEmpty(bindingInfo.CommandName)) throw new ArgumentException("bindingInfo.CommandName"); if (string.IsNullOrEmpty(bindingInfo.EventName)) throw new ArgumentException("bindingInfo.EventName"); } public void Bind() { ValidateBindingInfo(_bindingInfo); HookPropertyChanged(); HookEvent(); SetCommand(); } public void HookPropertyChanged() { var dataContext = Targetobject.DataContext as INotifyPropertyChanged; if (dataContext == null) return; dataContext.PropertyChanged -= DataContextPropertyChanged; dataContext.PropertyChanged += DataContextPropertyChanged; } private void DataContextPropertyChanged(object sender,PropertyChangedEventArgs e) { if (e.PropertyName == _bindingInfo.CommandName) SetCommand(); } private void SetCommand() { var dataContext = Targetobject.DataContext; if (dataContext == null) return; var propertyInfo = dataContext.GetType().GetProperty(_bindingInfo.CommandName); if (propertyInfo == null) throw new ArgumentException("commandName"); Command = propertyInfo.GetValue(dataContext,null) as ICommand; } private void HookEvent() { var eventInfo = Targetobject.GetType().GetEvent( _bindingInfo.EventName,BindingFlags.Public | BindingFlags.Instance); if (eventInfo == null) throw new ArgumentException("eventName"); eventInfo.RemoveEventHandler(Targetobject,GetEventMethod(eventInfo)); eventInfo.AddEventHandler(Targetobject,GetEventMethod(eventInfo)); } private Delegate _method; private Delegate GetEventMethod(EventInfo eventInfo) { if (eventInfo == null) throw new ArgumentNullException("eventInfo"); if (eventInfo.EventHandlerType == null) throw new ArgumentException("EventHandlerType is null"); if (_method == null) { _method = Delegate.CreateDelegate( eventInfo.EventHandlerType,this,GetType().getmethod("OnEventRaised",BindingFlags.NonPublic | BindingFlags.Instance)); } return _method; } private void OnEventRaised(object sender,EventArgs e) { ExecuteCommand(); } } public class EventBehaviorCollection : List<EventBehavior> { }
翻译完毕,本人将继续制作有关WPF和WCF相关文章的翻译,如果有不错的文章可以推荐
转载请注明文章出处,表示对作者的尊重,谢谢……
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。