通过Attached Property给控件绑定Command(一)
发布日期:2021-05-09 05:12:12 浏览次数:19 分类:精选文章

本文共 2725 字,大约阅读时间需要 9 分钟。

  本篇以WPF程序为例说明。水平有限,如有错误的地方,欢迎批评指正。

  首先来看一段XAML,将ViewModel中的Command上绑定到Button上,这样在点击Button时,会触发ViewModel中的Command的Execute方法。

  这样的好处是View中就不用写Button的处理逻辑了,可以通过ViewModel来进行单元测试,而把View教给专业美工处理,而不是苦逼的程序员。

  问题是可以像Button这样直接使用Command绑定的控件并不多。那如何给其他没有Command属性的控件如何处理呢?

  最简单的方法是仍然使用类似winform的事件,然后在View.cs文件中调用ViewModel中的Command。

private void Rectangle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)        {            this.ViewModel.MouseLeftDownCommand.Execute(sender);        }

  这个方法的优点是简单、直观、好懂,随便一个新人加入团队就可以开始干活,一边干活一边去学习为啥要用Command,啥是View,ViewModel。

  那有没有高级一点方式呢,这个看上去蠢翻了……

  当然是可以更高级一点了,这里就要用到Attached Property附加属性了,附加属性其实就是特殊的Dependency Property依赖属性.

  不同的是他们可以不写在Dependency Object里,而通过静态的Get和Set方法设置Value,同时获得在XAML里的语法支持。

  这里推荐2篇有关依赖属性的文章,2位大牛的文章那绝对是深入浅出,分析的相当到位:

  周永恒:

  圣殿骑士:

  当然可以先跳过这2篇,先看以下Command是如何附加给一般的控件的,回头再来慢慢研究依赖属性。

  首先我们看一下在XAML中绑定的效果,是不是和Button的绑定有点类似呢,这里local是对CommandBinder所在命名空间的引用:

  要实现绑定,我们需要创建CommandBinder类,并将MouseLeftDownCommandBinderProperty这个Attached Property定义出来。

class CommandBinder     {        #region MouseLeftCommand        public static ICommand GetMouseLeftDownCommandBinder(DependencyObject obj)        {            return (ICommand)obj.GetValue(MouseLeftDownCommandBinderProperty);        }        public static void SetMouseLeftDownCommandBinder(DependencyObject obj, ICommand value)        {            obj.SetValue(MouseLeftDownCommandBinderProperty, value);        }        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...        public static readonly DependencyProperty MouseLeftDownCommandBinderProperty =            DependencyProperty.RegisterAttached("MouseLeftDownCommandBinder",            typeof(ICommand), typeof(CommandBinder), new PropertyMetadata(ValueChangedCallback));        private static void ValueChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)        {            UIElement element = d as UIElement;            if (element != null)            {                element.MouseLeftButtonDown += (sender, arg) => { (e.NewValue as ICommand).Execute(element); };            }        }        #endregion}

  定义好这个类后,就能在XAML中使用CommandBinder.MouseLeftDownCommandBinder这样的语法了。

  那么在CLR解析XAML并绑定MouseLeftDownCommand的时候,就会进入ValueChangedCallback方法了。然后我们就将Command的调用和MouseLeftButton事件关联起来。如此在鼠标左键点击的时候,就会通过Command来执行了。

  这个写法的好处是脱离了+=这样的事件定义,View.cs的代码会比较干净,更重要的是Command的绑定可以写在XAML的资源,模版中,而不用重复的写在cs文件中,诸如:

foreach ( var button in buttonCollections){     button += .......  }

  但是第二种写法仍然有些不足,比如每个事件我都得写一个特定的依赖属性。再比如说没有方法传参数。那是不是可以更进一步呢,请看下篇通过Attached Property给控件绑定Command(二),当然文章我还没写好……不过示例代码倒是剧透了下篇的内容,欢迎下载。代码是在VS 2012 Express for Desktop里写的,如打不开请转一下工程文件。

上一篇:通过Attached Property给控件绑定Command(二)
下一篇:【翻译】Windows Phone运行模型概述

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2025年04月23日 12时13分31秒