2010-08-17 159 views

回答

18

下面是一個例子:

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

+0

+1,很好的例子 – Mizipzor 2010-08-17 12:44:51

+1

很好的例子!謝謝! – Vitalij 2010-08-17 13:08:59

0

您的UserControl將有一個代碼位於文件cs或vb後面,您必須實現接口ICommandSource,並且一旦實現了該接口,在某些情況下,您將不得不調用該命令並檢查CanExecute。

相關問題