WPF Events in ResourceDictionary for a ControlTemplate

前端 未结 1 1698
一整个雨季
一整个雨季 2020-12-02 23:34

I\'m currently trying to implement a Metro styled Window.
So i\'ve made the following styles inside a ResourceDictionary:



        
相关标签:
1条回答
  • 2020-12-02 23:58

    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();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题