zoukankan      html  css  js  c++  java
  • 通过Attached Property给控件绑定Command(一)

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

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

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

    <Button Command="{Binding MouseLeftDownCommand}"></Button>

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

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

     <Rectangle Width="100" Height="100" Fill="Blue" MouseLeftButtonDown="Rectangle_MouseLeftButtonDown"></Rectangle>
    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位大牛的文章那绝对是深入浅出,分析的相当到位:

      周永恒:http://www.cnblogs.com/zhouyongh/archive/2009/09/10/1564099.html

      圣殿骑士:http://www.cnblogs.com/KnightsWarrior/archive/2010/09/27/1836372.html

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

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

    <Rectangle Width="100" Height="100" Fill="Green" 
                       local:CommandBinder.MouseLeftDownCommandBinder="{Binding ViewModel.MouseLeftDownCommand, ElementName=window}" />

      要实现绑定,我们需要创建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里写的,如打不开请转一下工程文件。

    https://files.cnblogs.com/manupstairs/TestDPWpf.7z

  • 相关阅读:
    从nsurlsession、Alamofire到moya
    ssl是tcp的会话层与表示层
    Springboot+Thymeleaf+layui框架的配置与使用
    机械思维 信息思维
    路在何方—价值观、价值链与人生(草稿)
    世界由物质、能量、信息
    http_build_query()函数使用方法
    laravel 远程一对多实例
    MySQL中的float和decimal类型有什么区别
    mysql int(19) float(7,2) decimal(7,2)对比
  • 原文地址:https://www.cnblogs.com/manupstairs/p/2761688.html
Copyright © 2011-2022 走看看