Search code examples
wpfxamlresolutionscreen-size

xaml change resolution changes the view's size


I have a view that is fixed in height and width, and im currently using a 4k monitor. when i run my application on a 1080p monitor, its blew things up. i have some lines and paths that are set at a certain margin, and so is other controls.

i have tried binding to the screen width and height (see below), but it didn't kept the screen size fix when change to other resolution. i also set ResizeMode to NoResize

    Height="{Binding Source={x:Static SystemParameters.PrimaryScreenHeight}, Converter={k1:RatioConverter}, ConverterParameter='0.7'}"
    Width="{Binding Source={x:Static SystemParameters.PrimaryScreenWidth}, Converter={k1:RatioConverter}, ConverterParameter='0.7'}"

here is the converter i got from @berhauz

[ValueConversion(typeof(string), typeof(string))]
public class RatioConverter : MarkupExtension, IValueConverter
{
    private static RatioConverter _instance;

    public RatioConverter() { }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    { // do not let the culture default to local to prevent variable outcome re decimal syntax
        double size = System.Convert.ToDouble(value) * System.Convert.ToDouble(parameter, CultureInfo.InvariantCulture);
        return size.ToString("G0", CultureInfo.InvariantCulture);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    { // read only converter...
        throw new NotImplementedException();
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return _instance ?? (_instance = new RatioConverter());
    }

}

is there a way to fix the screen size on every resolution so the lines,paths,controls will not jump around?


Solution

  • i found the simple solution was to wrap everything in the viewbox and bind the height and width of the viewbox to the primary screen

    Height="{Binding Source={x:Static SystemParameters.PrimaryScreenHeight}, Converter={k1:RatioConverter}, ConverterParameter='0.7'}"
    Width="{Binding Source={x:Static SystemParameters.PrimaryScreenWidth}, Converter={k1:RatioConverter}, ConverterParameter='0.7'}"
    

    no matter what resolution you have, the contents inside my viewbox stayed the same and does not change sizes