2010-04-30 83 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