WPF自己定义命令Command


一、自己定义命令
自己定义命令必需要实现ICommand接口。例如以下代码所看到的:

/// <summary>
/// 自己定义的清除命令。

光脚丫思考 2014-7-31 06:51:32 /// </summary> public class ClearCommand : ICommand { public bool CanExecute(object parameter) { throw new NotImplementedException(); } /// <summary> /// 当命令可运行状态发生改变时,应激发该事件。 /// </summary> public event EventHandler CanExecuteChanged; /// <summary> /// 命令被运行,运行与业务相关的Clear逻辑。

/// </summary> /// <param name="parameter">运行命令的目标对象。

</param> public void Execute(object parameter) { IView view = parameter as IView; if (view != null) view.Clear(); } }


二、实现自己定义命令源
自己定义命令源需实现 ICommandSource接口。

/// <summary>
/// 自己定义命令源。崔有来 2014-7-31 06:54:26
/// </summary>
public class MyCommandSource : UserControl, ICommandSource
{
    public ICommand Command { get; set; }
    public object CommandParameter { get; set; }
    public System.Windows.IInputElement CommandTarget { get; set; }

    protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
    {
        base.OnMouseLeftButtonDown(e);

        // 在命令目标上运行命令。

if (this.CommandTarget != null && this.Command != null) this.Command.Execute(this.CommandTarget); } }


三、使用自己定义命令

ClearCommand ClearCmd = new ClearCommand();
this.MyCommandSource1.Command = ClearCmd;
this.MyCommandSource1.CommandTarget = this.MiniView1;




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WPF 中,可以使用 Command 属性将一个命令绑定到 Button 控件上,使得点击按钮时会执行该命令。具体步骤如下: 1. 创建一个实现了 ICommand 接口的命令类,例如: ``` public class MyCommand : ICommand { public event EventHandler CanExecuteChanged; public bool CanExecute(object parameter) { // 返回一个 bool 值,表示该命令是否可执行 return true; } public void Execute(object parameter) { // 执行命令的逻辑 } } ``` 2. 在 XAML 中定义 Button 控件,并将其 Command 属性绑定到上面创建的命令类的实例,例如: ``` <Button Content="Click Me" Command="{Binding MyCommand}" /> ``` 其中,Binding 的 Source 属性应该指向包含 MyCommand 属性的 ViewModel 对象。 3. 如果需要在 Command 执行前后进行一些操作,可以在 Button 控件上绑定 CommandParameter 属性和 CommandBinding 对象的相应事件,例如: ``` <Button Content="Click Me" Command="{Binding MyCommand}" CommandParameter="Hello, World!" CommandBindings="{StaticResource MyCommandBindings}" /> ``` 其中,MyCommandBindings 是一个定义CommandBinding 对象的资源,例如: ``` <Window.Resources> <CommandBindingCollection x:Key="MyCommandBindings"> <CommandBinding Command="{x:Static local:MyCommands.MyCommand}" Executed="MyCommand_Executed" /> </CommandBindingCollection> </Window.Resources> ``` 其中,MyCommands.MyCommand 是上面创建的命令类的静态属性,MyCommand_Executed 是一个在命令执行后调用的事件处理方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值