How to rotate a WPF Window?

2020-02-10 07:48发布

问题:

Is it possible to rotate a WPF Window by 45 degree, using xaml?

回答1:

First question: Why do you want to rotate the whole window?

If you really need it:
You can't rotate the normal WPF window. See: Rotate Window

You will have to create a borderless window and provide a UI to it. See: WPF Non-Client Area Design Techniques For Custom Window Frames

For rotated window look:
Set:

  • AllowTransparency property to true.
  • WindowStyle to None to remove window chrome
  • Background to Transparent

Include a border (or anything meaningful like rectangle, circle, ellipse, etc.) as content of the window and following properties of border:

  • white background (or any non-transparent color)
  • rotate transformation, and
  • smaller size (so as to fit when rotated within the window).

Border will provide the UI to your window.


Be aware of cavaets of creating own borderless window, as it requires you to provide the window interface like minimise, maximise, close buttons; and may require some unmanaged code.
Also, in sample code below, the border when rotated has to be kept within the bounds of the window, otherwise it (and your custom window) will be trimmed.

Sample code

<Window x:Class="CustomWindowStyle.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        AllowsTransparency="True" WindowStyle="None" Background="Transparent"
        Title="MainWindow" Height="600" Width="600">

        <Border BorderBrush="Green" BorderThickness="2" Background="White" Width="360" Height="360">
            <Border.RenderTransform>
                <RotateTransform Angle="-45" CenterX="180" CenterY="180"/>
            </Border.RenderTransform>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="23" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <Button Grid.Row="0" Content="X" Height="23" Width="23" Name="button1" HorizontalAlignment="Right" VerticalAlignment="Top" Click="button1_Click"/>
                <Grid Grid.Row="1">
                    <!--Main window content goes here-->
                    <TextBlock Text="Main window content goes here" HorizontalAlignment="Center" />
                </Grid>
            </Grid>
        </Border>
</Window>


回答2:

As far as I know you can't rotate an entire window, but you could put everything inside the window into a custom control and apply apply a RenderTransform object to the custom control.

Example (somewhat simple):

http://www.codeproject.com/KB/WPF/TransformationsIntro.aspx

-- Dan



标签: c# .net wpf xaml 3d