Search code examples
wpf

How can I create a WPF application which scales according to window height and is not affected by system dpi scaling?


I'm creating an industrial process monitoring and control application in C# using WPF for the UI. This application runs full-screen and will be deployed on a variety of windows computers which have different resolutions (1024x768, 1920x1080, and 1920x1200) and dpi scaling settings (100%, 125%, and 150%). I've been thinking about how I want to approach this problem and so far I've decided on this:

I design the whole ui for 1024x768, I design the layout to have flexible width in certain areas, and I scale everything according to height, ignoring the system dpi scaling.

Viewboxes don't seem to work because they destroy the layout completely. I'm also not sure I need to even combat the system dpi settings because I might naturally get the same effect when scaling by height if the height itself is measured in device-independent pixels.

Also, is there a better approach to what I'm trying to accomplish? There's a fixed amount of information I need to display on the screen regardless of resolution or scaling. Creating different layouts depending on the screen's aspect ratio would be very cool, but that may be too complex for now.


Solution

  • You may use a Viewbox with a child element with a fixed Height. Then determine the aspect ratio in a SizeChanged event handler and set the child's Width appropriately.

    <Grid SizeChanged="OnSizeChanged">
        <Viewbox>
            <Grid x:Name="scaledGrid" Height="768" Background="AliceBlue">
                <TextBlock Text="Hello, World"
                    VerticalAlignment="Center" HorizontalAlignment="Center"/>
            </Grid>
        </Viewbox>
    </Grid>
    

    The event handler:

    private void OnSizeChanged(object sender, SizeChangedEventArgs e)
    {
        var aspectRatio = e.NewSize.Width / e.NewSize.Height;
    
        scaledGrid.Width = scaledGrid.ActualHeight * aspectRatio;
    }