设为首页 收藏本站
查看: 1021|回复: 0

Attached Command for Windows 8 Metro Style in C#

[复制链接]

尚未签到

发表于 2015-5-22 07:19:08 | 显示全部楼层 |阅读模式
Introduction
  Windows 8 Developer Preview and Blend 5 Developer Preview edtion does not support the EventToCommandbehaviour yet (MVVM Light Toolkit is available for Metro:http://mvvmlight.codeplex.com but Blend behaviors not). And many developers want to implement the event to command in its MVVM pattern. So we need the Attached Command for Metro (Similar with the AttachedCommand in WPF).



Design the code
  Well, let's start.
  Usually, in MVVM pattern, we like to declare the value properties and the Commands in the ViewModel, which use the DataBinding on the View. And that can do the "Data Drives UI" job. But let us check the Metro Style App. Although it use the XAML, and WinRT compoenets, it still can use MVVM pattern as its architecture. Metro still supports DataBinding and yes we still can let "Data" drive the "Metro UI".
  However, it is easy to implement the properties and commands in ViewModel, but not easy to assign one UI Control event to one Command. In WPF, we could use the Blend SDK behaviour to assign one event to a command, or I usually recommend to design one AttachedCommand, like this did:http://marlongrech.wordpress.com/2008/12/13/attachedcommandbehavior-v2-aka-acb . But just checking the MVVM Light Toolkit for Metro, it cannot provide the EventToCommand behaviour amd the Blend 5 Developer Preview version does not provide the behaviour. So we just need to design one AttachedCommand for Metro.
  In out AttachedCommand class, we should declare two attached properties, Command and RoutedEvent property.



    ///
    /// Command attached property
    ///
    public static readonly DependencyProperty CommandProperty =
        DependencyProperty.RegisterAttached("Command",
        "Object",  // should be "Object" instead of "ICommand" interface, resolve the null reference exception
        typeof(AttachedCommand).FullName, new PropertyMetadata(DependencyProperty.UnsetValue));
    public static ICommand GetCommand(DependencyObject d)
    {
        return (ICommand)d.GetValue(CommandProperty);
    }
    public static void SetCommand(DependencyObject d, ICommand value)
    {
        d.SetValue(CommandProperty, value);
    }
    ///
    /// RoutedEvent property
    ///
    public static readonly DependencyProperty RoutedEventProperty =
        DependencyProperty.RegisterAttached("RoutedEvent",
        "String",
        typeof(AttachedCommand).FullName,
        new PropertyMetadata(String.Empty, new PropertyChangedCallback(OnRoutedEventChanged)));
    public static String GetRoutedEvent(DependencyObject d)
    {
        return (String)d.GetValue(RoutedEventProperty);
    }
    public static void SetRoutedEvent(DependencyObject d, String value)
    {
        d.SetValue(RoutedEventProperty, value);
    }
  
  We should register the Attached Property in Metro via the string of the type (similar with the Silverlight solution), and for Interface, we should use "Object" instead of. And not sure if it will be resolved in next Windows 8 version, but for interface, it will throw the NullReferenceException.
  Below is the property changed callback for RoutedEvent property:



    private static void OnRoutedEventChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        String routedEvent = (String)e.NewValue;
        if (!String.IsNullOrEmpty(routedEvent))
        {
            EventHooker eventHooker = new EventHooker();
            eventHooker.AttachedCommandObject = d;
            EventInfo eventInfo = GetEventInfo(d.GetType(), routedEvent);
            if (eventInfo != null)
            {
                eventInfo.AddEventHandler(d, eventHooker.GetEventHandler(eventInfo));
            }
        }
    }
  

  We need the EventInfo by reflecting the Metro DependecyObject. But in Metro, the reflection just can list the members which are declared in the current type directly. It cannot list all members inherits from the base type. So We should use one method to search the Event Member from its base types:



    ///
    /// Search the EventInfo from the type and its base types
    ///
    ///
    ///
    ///  
    private static EventInfo GetEventInfo(Type type, string eventName)
    {
        EventInfo eventInfo = null;
        eventInfo = type.GetTypeInfo().GetDeclaredEvent(eventName);
        if (eventInfo == null)
        {
            Type baseType = type.GetTypeInfo().BaseType;
            if (baseType != null)
                return GetEventInfo(type.GetTypeInfo().BaseType, eventName);
            else
                return eventInfo;
        }
        return eventInfo;
    }
  


  When the specific event is fired on the control, we should return the event handler. So there is an EventHooker that can return one "OnEventRaised" method, and execute the command in it:



  internal sealed class EventHooker
  {
      public DependencyObject AttachedCommandObject { get; set; }
      public Delegate GetEventHandler(EventInfo eventInfo)
      {
          Delegate del = null;
          if (eventInfo == null)
              throw new ArgumentNullException("eventInfo");
          if (eventInfo.EventHandlerType == null)
              throw new ArgumentNullException("eventInfo.EventHandlerType");
          if (del == null)
              del = this.GetType().GetTypeInfo().GetDeclaredMethod("OnEventRaised").CreateDelegate(eventInfo.EventHandlerType, this);
          return del;
      }
      private void OnEventRaised(object sender, object e)  // the second parameter in Windows.UI.Xaml.EventHandler is Object
      {
          ICommand command = (ICommand)(sender as DependencyObject).GetValue(AttachedCommand.CommandProperty);
          if (command != null)
              command.Execute(null);
      }
  }
  



How to use
  We should add one DelegateCommand or RelayCommand (ICommand) for Metro, which can help us to return the ICommand in the ViewModel. And we could bind this ICommand property on the AttachedCommand.Command property. Below is one DelegateCommand for Metro. And MVVM Light Toolkit provides the RelayCommand available for Metro also.



    public class DelegateCommand : ICommand
    {
        private readonly Predicate _canExecute;
        private readonly Action _execute;
        public event Windows.UI.Xaml.EventHandler CanExecuteChanged;
        public DelegateCommand(Action execute)
            : this(execute, null)
        {
        }
        public DelegateCommand(Action execute,
                       Predicate canExecute)
        {
            _execute = execute;
            _canExecute = canExecute;
        }
        public bool CanExecute(object parameter)
        {
            if (_canExecute == null)
                return true;
            return _canExecute(parameter);
        }
        public void Execute(object parameter)
        {
            _execute(parameter);
        }
        public void RaiseCanExecuteChanged()
        {
            if (CanExecuteChanged != null)
            {
                CanExecuteChanged(this, null);
            }
        }
    }
  

  Please note, WinRT EventHandler is different with the System.EventHandler. And Windows.UI.Xaml.EventHandler has two object parameters, the second one is not EventArgs.
  Then in the View, we just could set the AttachedCommand in any controls in Metro:




  

References
  


  • http://marlongrech.wordpress.com/2008/12/04/attachedcommandbehavior-aka-acb/
  • http://sachabarber.net/?p=514
  • http://social.msdn.microsoft.com/Forums/en-us/winappswithcsharp/thread/b4a1d607-9cd4-4472-b5c1-fe41167d9ea5

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-69317-1-1.html 上篇帖子: 重新想象 Windows 8 Store Apps (35) 下篇帖子: 菜鸟学Windows Phone 8开发(1)——创建第一个应用程序
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表