05 Feb 2010

WPF Quick Tip: How to Restrict Window Size in WPF 4

     

Another (paraphrased) question from twitter “How do I set the minimum and maximum sizes for my window in WPF”. The poster wanted to know how to constrain the size of their WPF window to a set minimum height/width and maximum height/width.

I originally replied with a complex answer referring back to my WPF Resize Behavior, because I completely forgot about the simple supported approach:

<Window x:Class="WpfApplication21.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="350"
        Width="525"
        MinHeight="300"
        MinWidth="500"
        MaxHeight="700"
        MaxWidth="900">
    <Grid>
        
    </Grid>
</Window>

The above markup constrains the size of the window to the sizes indicated by using the MinHeight, MinWidth, MaxHeight and MaxWidth properties. You can also set these from code at runtime.

Use this sparingly. It is generally not a great practice to constrain the size of your application window, or at least not the max size.

Share |
posted by Pete Brown on Friday, February 05, 2010
filed under:      

3 comments for “WPF Quick Tip: How to Restrict Window Size in WPF 4”

  1. Eric Hillsays:
    Hey, Pete,

    So you're making all these posts saying "do X in WPF 4" when your tips are not new to WPF 4; it's been that way all along. What with WPF 4 on the verge of coming out, it's a tad confusing. Why not say "How to restrict window size in WPF", and just put "WPF 4" on posts that are really something that's new in WPF 4?

    Thanks,

    Eric
  2. Pete Brownsays:
    @Eric

    Probably a good idea, thanks. I was used to writing "WPF 4" because I supply source code alongside the videos, and the source is VS2010 project targeting WPF4.

    Pete
  3. Josh Einsteinsays:
    A nice feature would be the ability to restrict the aspect ratio. That would make it a lot easier to use a ViewBox to support a scalable window. I'm guessing in WPF you'd have to resort to using HwndSource and handling the resize messages.

Comment on this Post

Remember me