Nathan Friend
Nathan Friend

Reputation: 12834

Animating an element from the edge of the screen to the center

I'm writing a dialog box in WPF that I'd like to enter from the edge of the screen and animate to the center when it is shown. The dialog will need to stay positioned in the center of the screen even when the window is resized. This seems like it should be dead-simple to do in WPF, and yet I still haven't thought up a reliable way of accomplishing this effect. I'd prefer to use a pure "layout" approach as opposed to calculating the dialog's position using a binding.

In HTML/CSS, I would simply animate the dialog's left CSS property from 0' to 50%... is there a similar way to accomplish this effect in WPF?

Upvotes: 1

Views: 78

Answers (1)

Nathan Friend
Nathan Friend

Reputation: 12834

To accomplish the effect, I wrote my own Panel subclass that acts like Canvas but accepts percentage offsets instead of absolute offsets. This allowed me to animate a "modal" UserControl from 0% to 50% of the screen.

Here's the class on Github.

Usage is similar to Canvas:

<Window>
    <local:PercentagePanel>
        <Button local:PercentagePanel.Left=".10" local:PercentagePanel.Bottom=".5"
         Width="100" Height="40">Hello world!</Button>
    </local:PercentagePanel>
</Window>

Result:

Example of PercentagePanel

By default, the PercentagePanel positions its children based on the appropriate edge of each child (similar to CSS positioning). The PercentagePanel can also position its children relative to each child's center via the PositioningMode property:

<local:PercentagePanel PositioningMode="Center">

Here's the result of changing the PositioningMode property in the above example:

Example of PercentagePanel with PositioningMode="Center"

Upvotes: 1

Related Questions