您可以使用行为模式解决此问题。基本上,您创建一个具有两个依赖属性的自定义类:Command 和 CommandParameter。您还为这两个属性注册了一个处理程序。
在其中一个处理程序中,您将 TextBox 作为参数传递。现在您可以连接到您感兴趣的事件。如果现在调用已注册的事件处理程序之一,您可以使用绑定命令参数调用绑定命令。
这是一个代码示例:
public class CommandHelper
{
//
// Attached Properties
//
public static ICommand GetCommand(DependencyObject obj)
{
return (ICommand)obj.GetValue(CommandProperty);
}
public static void SetCommand(DependencyObject obj, ICommand value)
{
obj.SetValue(CommandProperty, value);
}
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(CommandHelper), new UIPropertyMetadata(null));
public static object GetCommandParameter(DependencyObject obj)
{
return (object)obj.GetValue(CommandParameterProperty);
}
public static void SetCommandParameter(DependencyObject obj, object value)
{
obj.SetValue(CommandParameterProperty, value);
}
public static readonly DependencyProperty CommandParameterProperty =
DependencyProperty.RegisterAttached("CommandParameter", typeof(object), typeof(CommandHelper), new UIPropertyMetadata(null));
//
// This property is basically only there to attach handlers to the control that will be the command source
//
public static bool GetIsCommandSource(DependencyObject obj)
{
return (bool)obj.GetValue(IsCommandSourceProperty);
}
public static void SetIsCommandSource(DependencyObject obj, bool value)
{
obj.SetValue(IsCommandSourceProperty, value);
}
public static readonly DependencyProperty IsCommandSourceProperty =
DependencyProperty.RegisterAttached("IsCommandSource", typeof(bool), typeof(CommandHelper), new UIPropertyMetadata(false, OnRegisterHandler));
//
// Here you can register handlers for the events, where you want to invoke your command
//
private static void OnRegisterHandler(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
FrameworkElement source = obj as FrameworkElement;
source.MouseEnter += OnMouseEnter;
}
private static void OnMouseEnter(object sender, MouseEventArgs e)
{
DependencyObject source = sender as DependencyObject;
ICommand command = GetCommand(source);
object commandParameter = GetCommandParameter(source);
// Invoke the command
if (command.CanExecute(commandParameter))
command.Execute(commandParameter);
}
}
和 Xaml:
<TextBox Text="My Command Source"
local:CommandHelper.IsCommandSource="true"
local:CommandHelper.Command="{Binding MyCommand}"
local:CommandHelper.CommandParameter="MyParameter" />