Question

I created a SecondaryWindow dynamically that has a WindowStyle set to None. Hence, I want to set its content to DragMove-able by overriding its OnMouseLeftButtonDown.

I could not figure out how to include the override function within the SecondaryWindow initialization statement

public class MainWindow
{
    Window SecondaryWindow = new Window
    {
        WindowStyle = System.Windows.WindowStyle.None,
        Content = new myUserControl(),
        Topmost = true,      

        // My failed attempt
        base.OnMouseLeftButtonDown += (object sender, MouseButtonEventArgs e) =>
        {
            base.OnMouseLeftButtonDown(e);
            base.DragMove();
        }
    };
}
Was it helpful?

Solution

Your question could more generally be asked as 'How to add a handler for an event in the object initializer?'. 'Object initializer' refers to a syntax like this:

Foo newFow = new Foo
{
   Foo.Property = someValue
};

Just to make sure you don't misunderstand something, OnMouseLeftButtonDown += smth does not override the event, but adds an event handler for the event.

That being said: You can't. C# doesn't support registering handlers on events in the object initializer:

// Not possible
Foo newFoo = new Foo
{ 
    Event += someHandler
};

Neither does C# let you set the event:

// Not possible
Foo newFoo = new Foo
{
   Event = someDelegate
};

However, you can work around this limitation, by wrapping the event of your class SecondaryWindow in a property:

public class SecondaryWindow : Window
{
   public MouseButtonEventHandler MouseLeftButtonDownSubscriber
   {
      set { MouseLeftButtonDown += value; }
   }
}

No you can initialize your object like this:

Window SecondaryWindow = new Window
{
    WindowStyle = System.Windows.WindowStyle.None,
    Content = new myUserControl(),
    Topmost = true,
    MouseLeftButtonDownSubscriber = (object sender, MouseButtonEventArgs e) =>
    {
        base.OnMouseLeftButtonDown(e);
        base.DragMove();
    }
};

I would not recommend it though, as it adds confusion for people not familiar with your code and there is probably no good reason to do this, apart from the convenience for you of using the object initializer. I would recommend to initialize the object and set the properties in the initializers, but to subscribe to its events where one would expect it, for example in the constructor of the parent window.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top