MyCommand.cs
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace DefineCommand { public class MyCommand : ICommand { public event EventHandler CanExecuteChanged; public bool CanExecute(object parameter) { throw new NotImplementedException(); } public void Execute(object parameter) { TextBox txtCmd = parameter as TextBox; if (txtCmd != null) { MessageBox.Show(txtCmd.Text); } } } }
MyCommandSource.cs
using System.Windows; using System.Windows.Input; using System.Windows.Controls; namespace DefineCommand { class MyCommandSource : TextBlock, ICommandSource { public ICommand Command { get; set; } public object CommandParameter { get; set; } public IInputElement CommandTarget { get; set; } //重写单击处理函数,注意由于事件的优先级不同,如果命令源是Button的话,下面的函数不起作用 protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) { base.OnMouseLeftButtonUp(e); if (this.CommandTarget != null) { this.Command.Execute(this.CommandTarget); } } } }
MainWindow.xaml
<Window x:Class="DefineCommand.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:DefineCommand" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"> <Border CornerRadius="5" BorderBrush="LightBlue" BorderThickness="2"> <Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <TextBox Text="自定义命令测试,请输入内容:" TextAlignment="Center" VerticalAlignment="Center" FontSize="18"/> <TextBox x:Name="myTxt" Height="40" Margin="18" Grid.Column="1"/> <local:MyCommandSource x:Name="mySource" Grid.Row="1" Grid.ColumnSpan="2" Text="单击此色块自定义命令测试" FontSize="23" TextAlignment="Center" VerticalAlignment="Center" Height="110" Width="410" Background="LightBlue"/> </Grid> </Border> </Window>
MainWindow.xaml.cs
using System.Windows; namespace DefineCommand { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); MyCommand myCmd = new MyCommand(); this.mySource.Command = myCmd; this.mySource.CommandTarget = this.myTxt; } } }
时间: 2024-10-10 01:15:08