12

您能否提供一个示例,说明您如何实现ICommandSource接口。因为我希望UserControl无法在 xaml 中指定命令的我的 具有这种能力。并且能够在用户单击CustomControl.

4

2 回答 2

24

这是一个例子:

public partial class MyUserControl : UserControl, ICommandSource
{
    public MyUserControl()
    {
        InitializeComponent();
    }



    public ICommand Command
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }

    public static readonly DependencyProperty CommandProperty =
        DependencyProperty.Register("Command", typeof(ICommand), typeof(MyUserControl), new UIPropertyMetadata(null));


    public object CommandParameter
    {
        get { return (object)GetValue(CommandParameterProperty); }
        set { SetValue(CommandParameterProperty, value); }
    }

    // Using a DependencyProperty as the backing store for CommandParameter.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty CommandParameterProperty =
        DependencyProperty.Register("CommandParameter", typeof(object), typeof(MyUserControl), new UIPropertyMetadata(null));

    public IInputElement CommandTarget
    {
        get { return (IInputElement)GetValue(CommandTargetProperty); }
        set { SetValue(CommandTargetProperty, value); }
    }

    // Using a DependencyProperty as the backing store for CommandTarget.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty CommandTargetProperty =
        DependencyProperty.Register("CommandTarget", typeof(IInputElement), typeof(MyUserControl), new UIPropertyMetadata(null));


    protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
    {
        base.OnMouseLeftButtonUp(e);

        var command = Command;
        var parameter = CommandParameter;
        var target = CommandTarget;

        var routedCmd = command as RoutedCommand;
        if (routedCmd != null && routedCmd.CanExecute(parameter, target))
        {
            routedCmd.Execute(parameter, target);
        }
        else if (command != null && command.CanExecute(parameter))
        {
            command.Execute(parameter);
        }
    }

}

请注意,该CommandTarget属性仅用于RoutedCommands

于 2010-08-17T12:42:35.863 回答
0

您的 UserControl 将在文件 cs 或 vb 后面有一个代码,您必须实现接口 ICommandSource,一旦您实现了该接口,在某些情况下您将不得不实际调用命令并检查 CanExecute。

于 2010-08-17T12:19:50.940 回答