码迷,mamicode.com
首页 > 其他好文 > 详细

mvvm command的使用案例

时间:2017-10-19 15:06:12      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:src   send   als   route   name   binding   sum   local   ons   

主界面如下:

技术分享

前台代码:

<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;
        }

    }
}

 

mvvm command的使用案例

标签:src   send   als   route   name   binding   sum   local   ons   

原文地址:http://www.cnblogs.com/1175429393wljblog/p/7692255.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!