Windows 8 MVVM AttachedCommand

来源:互联网 发布:网络配线架mdf 编辑:程序博客网 时间:2024/06/09 17:13

http://mvvmlight.codeplex.com/

http://www.cnblogs.com/wpf_gd/archive/2012/01/25/2329490.html

 

VM 和 View要分离, 特别是View里不能出现任何业务逻辑相关的代码, 比较难搞的是如何传递View上的事件给ViewModel, 有MVVM Lite可以用也有DelegateCommand/RelayCommand, 但是都出现一个传递参数的问题, 还不用的不爽, 看了上面的连个帖子后, 我用了一种办法可以直接把事件处理代码移动到Vm里去, 而且签名也基本不变(只需要改成public 就好了), 思路很简单, 在View里面注册时间处理方法, 实际调用时通过反射调用VM里对应的方法, 用起来太傻瓜了, 而且省了一大段ICommand 接口的使用。跟DelegateCommand/RelayCommand 说再见。

 

            if (runtimeEvent.EventHandlerType == typeof(RoutedEventHandler))  // Button click
            {
                Func<RoutedEventHandler, EventRegistrationToken> add = (a) =>
                {
                    return (EventRegistrationToken)runtimeEvent.AddMethod.Invoke(control, new object[] { a });
                };

                Action<EventRegistrationToken> remove = (a) =>
                {
                    runtimeEvent.RemoveMethod.Invoke(runtimeEvent, new object[] { a });
                };

                RoutedEventHandler handler = (a, b) =>
                {
                    object ViewModel = GetViewModel(d);
                    string methodName = (string)GetMethod(d);
                    MethodInfo method = ViewModel.GetType().GetRuntimeMethod(methodName, new Type[] { typeof(object), b.GetType() });
                    method.Invoke(ViewModel, new object[] { a, b });
                };

                WindowsRuntimeMarshal.AddEventHandler<RoutedEventHandler>(add, remove, handler);
            }

 

原创粉丝点击