zl程序教程

您现在的位置是:首页 >  其他

当前栏目

mvvm command的使用案例

案例 Command MVVM 使用
2023-09-14 08:57:07 时间

主界面如下:

前台代码:

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

    }
}