zoukankan      html  css  js  c++  java
  • WPF学习之路(六)Command

    在WPF中,命令绑定机制是相比于事件更高级的概念,把应用程序的功能划分为多个任务,任务由多种途径触发。

    应用Command Binding使代码更符合MVVM模式(Model-View-ViewModel),类似于MVC模式(Model-View-Control)。这两种模式在以后的BLOG中会有详细的介绍。目的都是为了更好的分离前后台逻辑。

    一个简单的Button

    <Button Content="Button" Click="Button_Click" />
    private void Button_Click(object sender, RoutedEventArgs e)
    {
            MessageBox.Show("Hello WPF");
    }

    前台显示需要通过Button_Click方法跟后台关联上,如果想更好的分离这两部分,将Click事件替换成Command

    自定义Command

    using System;
    using System.Windows;
    using System.Windows.Input;
    
    public class MyCommand : ICommand
    {
        public bool CanExecute(object parameter)
        {
            return true;
        }
    
        public event EventHandler CanExecuteChanged;
    
        public void Execute(object parameter)
        {
            MessageBox.Show("Hello WPF");
        }
    }
    <Button Content="Button" x:Name="btn1" />
    public MainWindow()
    {
      InitializeComponent();
      btn1.Command = new MyCommand();
    }

    现在逻辑已经被分离到MyCommand中了

    使用预定义Command

    ApplicationCommands提供了很多预定义Command

    <Button Content="Button" x:Name="btn2" Command="ApplicationCommands.Close"/>

    但是这些命令并没有实现 ("▔□▔)

    使用Command Binding添加逻辑

    public MainWindow()
    {
        InitializeComponent();var OpenCmdBinding = new CommandBinding(
            ApplicationCommands.Close,
            OpenCmdExecuted,
            OpenCmdCanExecute);
    
        this.CommandBindings.Add(OpenCmdBinding);
    }
    
    void OpenCmdExecuted(object target, ExecutedRoutedEventArgs e)
    {
        this.Close();
    }
    
    void OpenCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }

    有些控件没有Command属性

    <Button Grid.Row="2" Height="100" Width="100" HorizontalAlignment="Left" Content="Decrease"  Command="Slider.DecreaseLarge"  CommandTarget="{Binding  ElementName=slider}"/>
    <Slider Grid.Row="2" x:Name="slider"  Width="100"></Slider>
    <Button Grid.Row="2" Height="100" Width="100" HorizontalAlignment="Right" Content="Increase"  Command="Slider.IncreaseLarge"  CommandTarget="{Binding  ElementName=slider}"/>

    CommandParameter可以给命令传递一个值

    CommandTarget:触发的命令目标

    更多的Command介绍

    http://www.cnblogs.com/Curry/archive/2009/07/27/1531798.html

    http://www.cnblogs.com/gaixiaojie/archive/2010/09/01/1815015.html

    To be continue...

  • 相关阅读:
    论文阅读 | ExtremeNet:Bottom-up Object Detection by Grouping Extreme and Center Points
    论文阅读 | CornerNet:Detecting Objects as Paired Keypoints
    论文阅读 | FPN:Feature Pyramid Networks for Object Detection
    关于字符串 “*****AB**C*D*****” 中前缀、后缀和中间 '*' 的处理
    #include< > 和 #include” ” 的区别
    小朋友排队
    核桃的数量
    操作格子
    字串统计
    关联矩阵
  • 原文地址:https://www.cnblogs.com/alex09/p/4434464.html
Copyright © 2011-2022 走看看