2010-04-30 5 views
2

Savez-vous comment puis-je m'abonner à un événement de la base de mon customControl? J'ai un contrôle personnalisé avec des propriétés de dépendance:Abonnez-vous aux événements du bouton dans un contrôle personnalisé

public class MyCustomControl : Button 
{ 
    static MyCustomControl() 
    { 
     DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl))); 
    } 

    public ICommand KeyDownCommand 
    { 
     get { return (ICommand)GetValue(KeyDownCommandProperty); } 
     set { SetValue(KeyDownCommandProperty, value); } 
    } 
    public static readonly DependencyProperty KeyDownCommandProperty = 
    DependencyProperty.Register("KeyDownCommand", typeof(ICommand), typeof(MyCustomControl)); 

    public ICommand KeyUpCommand 
    { 
     get { return (ICommand)GetValue(KeyUpCommandProperty); } 
     set { SetValue(KeyUpCommandProperty, value); } 
    } 
    public static readonly DependencyProperty KeyUpCommandProperty = 
    DependencyProperty.Register("KeyUpCommand", typeof(ICommand), typeof(MyCustomControl)); 

    public ICommand KeyPressedCommand 
    { 
     get { return (ICommand)GetValue(KeyPressedCommandProperty); } 
     set { SetValue(KeyPressedCommandProperty, value); } 
    } 
    public static readonly DependencyProperty KeyPressedCommandProperty = 
    DependencyProperty.Register("KeyPressedCommand", typeof(ICommand), typeof(MyCustomControl)); 
} 

Et je whant pour vous abonner aux événements de boutons (comme MouseLeftButtonDown) pour exécuter un code dans mon CustomControl. Savez-vous comment faire quelque chose comme ça dans le constructeur?

static MyCustomControl() 
    { 
     DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl))); 
     MouseLeftButtonDownEvent += (object sender, MouseButtonEventArgs e) => "something"; 
    } 

Merci pour vous aider à

Répondre

2

J'ai trouvé la solution!

Vous devez simplement remplacer la méthode OnMouseLeftButtonDown. N'oubliez pas d'appeler base.OnMouseLeftButtonDown après votre code.

1

Eh bien, cela pourrait fonctionner. Si vous vouliez être libre de tout code-behind dans votre fichier xaml et que vous vouliez vous conformer à MVVM, alors je vous aurais suggéré de vous pencher sur les comportements attachés.

Voici un lien: http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx

Il est une très bonne ressource et m'a sauvé la semaine dernière.

+0

Merci Chris :) –

Questions connexes