[英]In WPF how do I implement ICommandSource to give my custom control ability to use Command from xaml?
Could you please provide a sample, of how do you implement the ICommandSource
interface. 能否请您提供一个示例,了解如何实现
ICommandSource
接口。 As I want my UserControl
, which doesn't have the ability to Specify command in xaml, to have this ability. 因为我想要我的
UserControl
,它不具备在xaml中指定命令的能力,以具备此功能。 And to be able to handle the command when user clicks on the CustomControl
. 并且能够在用户单击
CustomControl
时处理该命令。
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
请注意,
CommandTarget
属性仅用于RoutedCommands
您的UserControl将在文件cs或vb后面有一个代码,您必须实现接口ICommandSource,一旦实现它,在某些情况下您将必须实际调用该命令并检查CanExecute。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.