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

前端之家收集整理的这篇文章主要介绍了c# – 在WPF中如何实现ICommandSource以使我的自定义控件能够使用来自xaml的Command?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
可以请提供一个示例,说明如何实现ICommandSource接口.当我想要我的UserControl,它没有能力在xaml中指定命令,以具有这种能力.并且当用户点击CustomControl时,能够处理命令.

解决方法

这里有一个例子: @H_502_6@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

猜你在找的C#相关文章