WPF Events in ResourceDictionary for a ControlTemplate

A ResourceDictionary can have code behind just like Windows etc. so you could add an event handler and call DragMove from there

Setting up the code behind requires a couple of steps.

  • If your ResourceDictionary is called MetroStyleResourceDictionary.xaml you add a new file in Visual Studio in the same folder called MetroStyleResourceDictionary.xaml.cs
  • The code behind file should then look like this

    public partial class MetroStyleResourceDictionary
    {
        //...
    }
    
  • After that you need to add the x:Class attribute to the Xaml file

    <ResourceDictionary x:Class="YourNamespace.MetroStyleResourceDictionary"
                        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <!--...-->
    </ResourceDictionary>
    

Now you can add an event handler to the dragRectangle for MouseLeftButtonDown. You’ll also need to get a hold of the Window so binding that to Tag might be a good idea

<Rectangle Name="dragRectangle"
           MouseLeftButtonDown="dragRectangle_MouseLeftButtonDown"
           Tag="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
           .../>

And finally you can add the event handler to the code behind file which will look like this

public partial class MetroStyleResourceDictionary
{
    void dragRectangle_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        Rectangle dragRectangle = sender as Rectangle;
        Window window = dragRectangle.Tag as Window;
        if (window != null)
        {
            window.DragMove();
        }
    }
}

Leave a Comment