我想通過下面提供的類向wpf控件添加一些功能。如何將CommandParameter添加到文本
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: 伊戈爾的變異與我的變化:
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); }
其中'Command.Execute(對象)'應該是叫什麼?因爲它是唯一需要命令參數的地方,答案直接取決於它 – dvvrd