In WPF how do I implement ICommandSource to give my custom control ability to use Command from xaml?

六月ゝ 毕业季﹏ 提交于 2019-12-21 07:38:06

问题


Could you please provide a sample, of how do you implement the ICommandSource interface. As I want my UserControl, which doesn't have the ability to Specify command in xaml, to have this ability. And to be able to handle the command when user clicks on the CustomControl.


回答1:


Here's an example :

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);
        }
    }

}

Note that the CommandTarget property is only used for RoutedCommands




回答2:


Your UserControl will have a code behind file cs or vb, you have to implement the interface ICommandSource, and once you implement that, in some event you will have to actually invoke the command and also check CanExecute.



来源:https://stackoverflow.com/questions/3502127/in-wpf-how-do-i-implement-icommandsource-to-give-my-custom-control-ability-to-us

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!