声明一个RoutedCommand或RoutedUICommand对象,使用方式和命令库中命令一样。
实例演示:自定义清除命令,实现点击按钮即可清除文本框中的内容
xaml前台代码:
<Window x:Class="CommandTest.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:CommandTest"
mc:Ignorable="d"
Title="MainWindow" Height="230" Width="300">
<StackPanel>
<TextBox x:Name="txt1" Width="200" Margin="10,20,10,10"></TextBox>
<Button x:Name="btn1" Width="100" Margin="10">清除</Button>
</StackPanel>
</Window>
对应C#后台代码:
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 CommandTest
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
InitializeCommand(); //初始化命令
}
//声明并定义命令
private RoutedCommand ClearCmd = new RoutedCommand();
private void InitializeCommand()
{
CommandBinding cb = new CommandBinding();
cb.Command = ClearCmd;
cb.CanExecute += Clear_CanExecute;
cb.Executed += Clear_Executed;
this.CommandBindings.Add(cb);
btn1.Command = ClearCmd;
}
private void Clear_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = !string.IsNullOrEmpty(txt1.Text);
}
private void Clear_Executed(object sender, ExecutedRoutedEventArgs e)
{
txt1.Text = "";
}
}
}
效果演示: