Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a transparent WPF window with the default title bar functionality?

Tags:

wpf

I am writing a little application using WPF. I want to make the window's inner bits transparent, with opaque controls, while the title bar (and the ability to move, minimize, maximize, resize, close etc) remains solid.

However for some reason WPF doesn't allow me to use the default title bar when setting AllowTransparency to true, forcing me to set WindowStyle to None, which isn't what I want. Is there a workaround for this?

My application and problem aren't so advanced that starting from scratch is an issue.

like image 493
JoseAyeras Avatar asked Apr 01 '19 01:04

JoseAyeras


1 Answers

To achieve window transparency, you need to set the following

WindowStartupLocation="CenterScreen"
AllowsTransparency ="True"
WindowStyle="None"
Background="Transparent"

Maximize, minimize, and close can be achieved by yourself:

XAML:

  <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="30"></RowDefinition>
        <RowDefinition></RowDefinition>
    </Grid.RowDefinitions>
    <Rectangle Fill="Brown" MouseLeftButtonDown="Rectangle_MouseLeftButtonDown"></Rectangle>
    <WrapPanel HorizontalAlignment="Right" VerticalAlignment="Top" Height="30" Width="Auto">
        <Button Width="20" Height="20" Margin="5" Click="Button_Click_1">_</Button>
        <Button Width="20" Height="20" Margin="5" Click="Button_Click_2">口</Button>
        <Button Width="20" Height="20" Margin="5" Click="Button_Click_3">X</Button>
    </WrapPanel>
</Grid>

Code:

    /// <summary>
    /// Min
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        if (this.WindowState != WindowState.Minimized)
        {
            this.WindowState = WindowState.Minimized;
        }
    }

    /// <summary>
    /// Max
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Button_Click_2(object sender, RoutedEventArgs e)
    {
        if (this.WindowState != WindowState.Maximized)
        {
            this.WindowState = WindowState.Normal;
        }
    }

    /// <summary>
    /// Close
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Button_Click_3(object sender, RoutedEventArgs e)
    {
        this.Close();
    }

    /// <summary>
    /// DragMove
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Rectangle_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        this.DragMove();
    }
like image 151
juster zhu Avatar answered Oct 28 '22 17:10

juster zhu