可以请提供一个示例,说明如何实现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
原文地址:https://www.jb51.cc/csharp/94563.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。