2010-04-30 84 views
2

您知道如何訂閱我的customControl的基礎事件嗎? 我曾與一些依賴屬性的自定義控制:將按鈕的事件訂閱到自定義控件中

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)); 
} 

我whant訂閱按鈕的事件(如的MouseLeftButtonDown)在我customControl運行一些代碼。

你知道我該如何在構造函數中做這樣的事嗎?

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

感謝您幫助

回答

2

我找到了解決辦法!

你只需要重寫OnMouseLeftButtonDown方法。不要忘記在代碼後調用base.OnMouseLeftButtonDown。

1

那麼,這可以工作。如果你想在你的xaml文件中沒有任何代碼隱藏,並希望遵守MVVM,那麼我會建議你看看附加行爲。

這裏是一個鏈接:http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx

這是一個非常好的資源和上週剛剛救了我。

+0

謝謝克裏克:) – 2010-05-01 12:37:26