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;
}
}
}
相关文章
- php简单的检测文件名后缀案例
- MongoDB中创建与删除索引对业务的影响案例
- Echarts5.3.2可视化案例-应用篇
- 系统分析师案例必备知识点汇总---2023系列文章四
- 可变长子网掩码划分案例
- 【愚公系列】2023年02月 .NET CORE工具案例-对象映射Master的使用
- 【Netty】NIO 选择器 ( Selector ) 通道 ( Channel ) 缓冲区 ( Buffer ) 网络通信案例
- 实战案例:实现CentOS 7 编译安装基于 fastcgi 模式的多虚拟主机的wordpress和discuz的LAMP架构
- 【信息诈骗典型案例】之“黑客盗号”
- operationMySQL 56服务器误操作案例分析(5.6mysql mis)
- Oracle 实现实时应用的示范(oracle 使用案例)
- Android列表实现(2)_游标列表案例讲解