I'm trying to find way how to programatically adaptive screen in the UWP app, but I can't get any related idea, is there anything like that?
1 Answer
Adaptive Triggers are the best solution for layout changes based on app's size. For examples see: https://www.microsoft.com/en-gb/developers/articles/week03aug15/designing-with-adaptive-triggers-for-windows-10/ .
A simple example for two buttons:
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState x:Name="Narrow">
</VisualState>
<VisualState x:Name="Wide">
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="600" />
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="TestButton2.Visibility" Value="Visible" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<StackPanel>
<Button x:Name="TestButton" Content="Test button" />
<Button x:Name="TestButton2" Content="Test button" Visibility="Collapsed" />
</StackPanel>
</Grid>
Once the app is wider than 600 pixels, the second button will become visible.
Other approaches
You can change the layout of the page in reaction to size changes using the Page's SizeChanged event, which is fired each time the user resizes the page. This is not a clean approach however and you are much better suited using the built-in adaptive triggers for this.
//in the page's constructor wire-up the SizeChanged event
this.SizeChanged += MainPage_SizeChanged;
private void MainPage_SizeChanged( object sender, SizeChangedEventArgs e )
{
if ( e.NewSize.Width < 768 )
{
//some layout changes
}
else if (e.NewSize.Width < 1024)
{
//some layout changes
}
else
{
//etc.
}
}
You can also manually switch the current VisualState for the page from code.
First define some VisualStates in XAML:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CustomGroup">
<VisualState x:Name="ShowButtonState" />
<VisualState x:Name="HideButtonState">
<VisualState.Setters>
<Setter Target="TestButton.Visibility" Value="Collapsed" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Button x:Name="TestButton" Content="Test button" />
</Grid>
And then switch the states in code:
if ( someCondition )
{
VisualStateManager.GoToState( this, "HideButtonState", false );
}
else
{
VisualStateManager.GoToState( this, "ShowButtonState", false );
}
MainPage.xamland launch it to see how it behaves. TheAdaptiveTriggerfor theWidestate is triggered when the app's window is wider than 600 pixels.