Search code examples
c#wpfresolution

Automatic resize of semi-fixed-sized WPF windows using Converters while listening to resolution change


I'm currently creating a css media/Android layout-like behavior in WPF. Basically, I have resolution categories based on three values for screen width: 800px, 1280px, and 1920px.

There are three corresponding resource dictionaries that contain Int32 values with keys for the UI elements. A sample entry is:

<sys:Int32 x:Key="initial_screen_width">1600</sys:Int32>

My IConverter simply checks the screen resolution level (the one based on screen width) and returns the key in the dictionary with the corresponding resolution:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    int dimension = 0;
    object value2 = value;
    string resourceId = (string)parameter;

    if(resourceId is string)
    {
        dimension = GetDimension(resourceId, GetResolutionLevel());
    }

    return dimension;
}

Lastly, I simply bind the UserControl attributes with the converter:

<UserControl
...
Height="{Binding Converter={StaticResource LayoutDimensionConverter}, ConverterParameter=initial_screen_height}"
...
>

It work perfectly fine-- the corresponding dimensions are returned. However, I can't seem to find a way to handle resolution change (updating the UI to adjust again). I found some links regarding the use of UpdateTarget

so I tried using the system parameters as static variables, but the resolution change is not detected. Are there ways to do this?


Solution

  • This was done using SystemEvents.DisplaySettingsChanged.

            public SomeView()
            {
                SystemEvents.DisplaySettingsChanged += SystemEvents_DisplaySettingsChanged;
            }
    
            private void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e)
            {
                // Refreshes UI
                var dataContext = DataContext;
                DataContext = null;
                DataContext = dataContext;
            }
    

    Whenever the screen resolution is changed, the DataContext is reset and all the value converters are fired again.