Search code examples
wpf

Custom control minimize button


I want to create a custom minimize button with some specific style so I can use this button in many WPF windows, is there any way to add a click event to that button so it can minimize any form when the button is clicked .. so I don't have to write in each form

this.WindowState = WindowState.Minimized;

I want to do the same for Close button

I used Custom Control and I've succeeded in using the style I wanted for the button but I can't add the Event

This is the code in the custom Control

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApp2">


    <Style TargetType="{x:Type local:CustomControl1}" BasedOn="{StaticResource {x:Type Button}}">
        <Setter Property="Background" Value="Yellow"></Setter>
        <Setter Property="Width" Value="100"></Setter>
        <Setter Property="Height" Value="100"></Setter>
    </Style>
    
    
</ResourceDictionary>

and this is the code in the MainForm <control:CustomControl1 ></control:CustomControl1>


Solution

  • Add a Click event to your Minimize button in your CustomControl1.xaml and the following handler to your CustomControl1.xaml.cs file:

    private void MinimizeButton_Click(object sender, RoutedEventArgs e)
    {
        Window ownerWindow = Window.GetWindow(this);
        ownerWindow.WindowState = WindowState.Minimized;
    }
    

    When you click this button, whatever Window that owns it, the Window will be minimized.