zoukankan      html  css  js  c++  java
  • mvvm command的使用案例

    主界面如下:

    前台代码:

    <Window x:Class="WpfApp1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:WpfApp1"
            mc:Ignorable="d"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
            <StackPanel x:Name="stackPanel" Margin="20">
                <Button x:Name="button1" Content="命令测试" />
                <TextBox x:Name="textBoxA" />
            </StackPanel>

        </Grid>
    </Window>

    后台代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;

    namespace WpfApp1
    {
        /// <summary>
        /// MainWindow.xaml 的交互逻辑
        /// </summary>
        public partial class MainWindow : Window
        {
            private RoutedCommand clearCmd = new RoutedCommand("Clear", typeof(MainWindow));

            public MainWindow()
            {
                InitializeComponent();
                this.button1.Command = clearCmd;
                this.clearCmd.InputGestures.Add(new KeyGesture(Key.C, ModifierKeys.Alt));//使用快捷键

                // 指令命令目标
                this.button1.CommandTarget = this.textBoxA;

                // 创建命令绑定
                CommandBinding cb = new CommandBinding();
                cb.Command = this.clearCmd;
                cb.CanExecute += cb_CanExecute;
                cb.Executed += cb_Executed;

                this.stackPanel.CommandBindings.Add(cb);

            }
            void cb_Executed(object sender, ExecutedRoutedEventArgs e)
            {
                this.textBoxA.Clear();
                e.Handled = true;
            }

            void cb_CanExecute(object sender, CanExecuteRoutedEventArgs e)
            {
                if (string.IsNullOrEmpty(this.textBoxA.Text))
                    e.CanExecute = false;
                else
                    e.CanExecute = true;

                e.Handled = true;
            }

        }
    }

  • 相关阅读:
    升级ios 不能连原本的xcode /xcode不能抓帧/换xcode版本 build fail
    BlackBerry Key2 键盘扩展
    再议C风格变量声明
    怎样去除SVN中的某个版本之前的所有版本
    mysql 常用基础语句
    乱码问题
    sql server
    MySQL查询今天、昨天、上周、近30天、去年等的数据的方法
    java 时间转换
    sql server 日期
  • 原文地址:https://www.cnblogs.com/1175429393wljblog/p/7692255.html
Copyright © 2011-2022 走看看