我正在尝试通过下面介绍的类向 wpf 控件添加一些功能。
namespace ATCheckerView
{
public class AttachedMouseBinding
{
public static ICommand GetCommand(DependencyObject obj)
{
return (ICommand)obj.GetValue(CommandProperty);
}
public static void SetCommand(DependencyObject obj, Object value)
{
obj.SetValue(CommandProperty, value);
}
public static Object GetCommandParameter(DependencyObject obj)
{
return (ICommand)obj.GetValue(CommandParameterProperty);
}
public static void SetCommandParameter(DependencyObject obj, Object value)
{
obj.SetValue(CommandParameterProperty, value);
}
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(AttachedMouseBinding),
new FrameworkPropertyMetadata(CommandChanged));
public static readonly DependencyProperty CommandParameterProperty =
DependencyProperty.RegisterAttached("CommandParameter", typeof(object), typeof(AttachedMouseBinding),
new FrameworkPropertyMetadata(CommandParameterChanged));
private static void CommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var fe = d as FrameworkElement;
var command = e.NewValue as ICommand;
if (command == null) return;
var inputBinding = new InputBinding(command, new MouseGesture(MouseAction.LeftDoubleClick));
fe.InputBindings.Add(inputBinding);
}
private static void CommandParameterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
//var fe = d as FrameworkElement;
// var parameter = e.NewValue as Object;
}
}
}
我这样使用它:
<TextBlock Grid.Column="0" HorizontalAlignment="Stretch"
Tag="{Binding ElementName=Root, Path=DataContext}"
Text="{Binding Path=path, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
ContextMenu="{StaticResource SchemeContextMenu}"
local:AttachedMouseBinding.Command="{Binding ElementName=Root, Path=DataContext.vclient.OpenInViewer}"
local:AttachedMouseBinding.CommandParameter="{Binding}">
</TextBlock>
我的问题是:现在将 CommandParameter 发送到命令
UPD:Igor 的变体与我的更改:
private static void OnMouseLeftClick(object sender, RoutedEventArgs e)
{
var me = e as MouseButtonEventArgs;
if (me != null && me.ClickCount != 2) return;
FrameworkElement control = sender as FrameworkElement;
ICommand command = (ICommand)control.GetValue(CommandProperty);
object commandParameter = control.GetValue(CommandParameterProperty);
if (command.CanExecute(commandParameter))
command.Execute(commandParameter);
}