加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在WPF中如何实现ICommandSource以使我的自定义控件能够使

发布时间:2020-12-15 06:48:31 所属栏目:百科 来源:网络整理
导读:可以请提供一个示例,说明如何实现ICommandSource接口.当我想要我的UserControl,它没有能力在xaml中指定命令,以具有这种能力.并且当用户点击CustomControl时,能够处理命令. 解决方法 这里有一个例子: public partial class MyUserControl : UserControl,ICom
可以请提供一个示例,说明如何实现ICommandSource接口.当我想要我的UserControl,它没有能力在xaml中指定命令,以具有这种能力.并且当用户点击CustomControl时,能够处理命令.

解决方法

这里有一个例子:
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),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,etc...
    public static readonly DependencyProperty CommandTargetProperty =
        DependencyProperty.Register("CommandTarget",typeof(IInputElement),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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读