本人实在是太懒了,实在是不想引用DLL
所以自定义 MyTextBlock , 使用其MouseLeftClick来触发ICommand
namespace MyControls20210528 {
class MyTextBlock : TextBlock, ICommandSource
{
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(ICommand), typeof(MyTextBlock),
new PropertyMetadata((ICommand)null,new PropertyChangedCallback(CommandChanged)));
public static readonly DependencyProperty CommandParameterProperty =
DependencyProperty.Register("CommandParameter", typeof(object), typeof(MyTextBlock));
public static readonly DependencyProperty CommandTargetProperty =
DependencyProperty.Register("CommandTarget", typeof(IInputElement), typeof(MyTextBlock));
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
public object CommandParameter
{
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
public IInputElement CommandTarget
{
get { return (IInputElement)GetValue(CommandTargetProperty); }
set { SetValue(CommandTargetProperty, value); }
}
private static void CommandChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)
{
MyTextBlock myTxtb = d as MyTextBlock;
if(myTxtb!=null)
{
ICommand oldCommand = e.OldValue as ICommand;
ICommand newCommand = e.NewValue as ICommand;
myTxtb.HookUpCommand(oldCommand, newCommand);
}
}
private void HookUpCommand(ICommand oldCommand, ICommand newCommand)
{
if (oldCommand != null)
{
oldCommand.CanExecuteChanged -= CanExecuteChanged;
}
if (newCommand != null)
{
newCommand.CanExecuteChanged += CanExecuteChanged;
}
}
private void CanExecuteChanged(object sender, EventArgs e)
{
RoutedCommand command = this.Command as RoutedCommand;
if (command != null)
{
this.IsEnabled = command.CanExecute(CommandParameter, CommandTarget);
}
else if (this.Command != null)
{
this.IsEnabled = this.Command.CanExecute(CommandParameter);
}
}
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
RoutedCommand command = Command as RoutedCommand;
if (command != null)
command.Execute(CommandParameter, CommandTarget);
else if (Command != null)
this.Command.Execute(CommandParameter);
}
}
}
xaml中如何使用:
xmlns:MyTxtb ="clr-namespace:MyControls20210528 "
<MyTxtb:MyTextBlock Text="下一个" Command="{Binding CMD_ClickTheLabel}"/>
在Command绑定正确的情况下,鼠标左键能够触发
参考: https://docs.microsoft.com/zh-cn/dotnet/desktop/wpf/advanced/how-to-implement-icommandsource?redirectedfrom=MSDN&view=netframeworkdesktop-4.8
原文:https://www.cnblogs.com/wandia/p/14821583.html