0

I am WPF newbie. In a WPF sample code I am looking at, there is a mouse event handler as follows:

namespace Recipe_04_15
{
    public class DragCanvasControl : Canvas
    {
        ...
        static DragCanvasControl()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(DragCanvasControl),
                new FrameworkPropertyMetadata(typeof(DragCanvasControl)));
        }
        protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            ...
        }
...

What I don't understand is how the OnPreviewMouseLeftButtonDown method is wired to the mouse button down event. The XAML code does not have events specified?

0

2 Answers 2

2

The function is already wired in the UIElement class.
http://msdn.microsoft.com/en-us/library/system.windows.uielement.previewmouseleftbuttondown.aspx

Since you inherit from the canvas you also inherit also from UIElement somewhere deeper.
DragCanvasControl => Canvas => Panel => FrameworkElement => UIElement

By overiding the OnPreviewMouseLeftButtonDown from UIElement you get access to this event.

1
  • @Kris: Thank you, marked it as the answer. I had not noticed the override keyword. (WPF learning curve is steep!)
    – Sabuncu
    Commented Jan 6, 2012 at 15:54
0

If it is not in the XAML, it has to be attached in the code-behind. If it is not, the method will not be executed.

Be aware that you are actually looking for the PreviewMouseLeftButtonDown event and not some Click or MouseDown.

2
  • For Click fo instance .... Inside [Windows1].xaml.cs you will see: private void button1_Click(object sender, RoutedEventArgs e) { } For this inside the [Windows1].g.i.cs you will see: #line 6 "..\..\Window1.xaml" this.button1.Click += new System.Windows.RoutedEventHandler(this.button1_Click);
    – tryme
    Commented Jan 6, 2012 at 15:38
  • [offtopic] would not it be nice to be able to format comments :P
    – tryme
    Commented Jan 6, 2012 at 15:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.