ITKeyword,专注技术干货聚合推荐

注册 | 登录

MVVM之旅-给任意的事件绑定命令(Adventures in MVVM – Binding Commands to ANY Event)

wziyx513225244 分享于 2011-10-03

2019阿里云双12.12最低价产品入口(新老用户均可),
地址https://www.aliyun.com/minisite/goods

 原文标题:Adventures in MVVM – Binding Commands to ANY Event 当我实现MVVM模式时,令我最为头疼一件事是需要给事件绑定命令。当我使用Prism框架时,我得到一个Button.Click的命令绑定,但是每一个其他的时间都需要单独的进行处理。做这些的时候,需要很多的容易出错的样板代码。在我过去的工作岗位上,我发表一些代码来减轻疼痛。然而,仍需要你针对每一个你想进行绑定的事件写一个新的行为和附加内容。 有一段时间了,我的想法只是直接绑定命令到时间。在这期间我遇到很多困难。例如,每一个事件处理都有一个同的事件参数类型。这需要所有的处理都是动态的。我仍然不能创建一个内置的命令绑定--我将确信对每一个单一控件绑定到超过1个的事件。因此我需要创建一个绑定的集合。创建结构体数据就是给自己创造麻烦---绑定仅工作在VisualTree的FrameWorkElements上。这需要我来写自己的绑定基于我的通用的行为。 以下是非常松散的基础下Chinch MVVM框架。我测试了这些代码在Silverlight和WPF,并且运行真的不错! 假定我有一个像如下的ViewMode: 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),

typeof(Control),

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),

new PropertyMetadata(null, 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相关文章的翻译,如果有不错的文章可以推荐 转载请注明文章出处,表示对作者的尊重,谢谢……

 原文标题:Adventures in MVVM – Binding Commands to ANY Event 当我实现MVVM模式时,令我最为头疼一件事是需要给事件绑定命令。当我使用Prism框架时,我得到一个Button.Click的命令绑定,但

相关阅读排行


用户评论

游客

相关内容推荐

最新文章

×

×

请激活账号

为了能正常使用评论、编辑功能及以后陆续为用户提供的其他产品,请激活账号。

您的注册邮箱: 修改

重新发送激活邮件 进入我的邮箱

如果您没有收到激活邮件,请注意检查垃圾箱。