在WPF?如何实施ICommandSource给我用命令的XAML自定义控件的能力? [英] In WPF how do I implement ICommandSource to give my custom control ability to use Command from xaml?
本文介绍了在WPF?如何实施ICommandSource给我用命令的XAML自定义控件的能力?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请您提供您怎么落实 ICommandSource
界面的样本。正如我希望我的用户控件
,它不必在XAML指定命令,有这种能力的能力。并能在用户点击来处理该命令的 CustomControl
。
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
.
推荐答案
下面是一个例子:
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);
}
}
}
请注意, CommandTarget
属性仅用于 RoutedCommands
这篇关于在WPF?如何实施ICommandSource给我用命令的XAML自定义控件的能力?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文