How do I capture the mobile phone horizontal screen event?
My code needs to be triggered when the mobile phone is horizontal.
How do I capture the mobile phone horizontal screen event?
My code needs to be triggered when the mobile phone is horizontal.
Hi 80240195,
Welcome to our Microsoft Q&A platform!
According to the document: Reacting to Changes in Orientation, we know that we can override the OnSizeAllocated method on a Page to monitor changes in orientation.
Here is the simple demo.
private double width = 0;
private double height = 0;
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height);
if (this.width != width || this.height != height)
{
this.width = width;
this.height = height;
if (width < height)
{
Debug.WriteLine("Portrait");
}
else
{
Debug.WriteLine("Landscape");
}
}
}
Also, the document mentioned the DeviceDisplay which exposes event "MainDisplayInfoChanged". For more info, you can refer to Xamarin.Essentials: Device Display Information.
However, it should be noted that some problems may occur after subscribing to the event. And here is a related thread on GitHub: DisplayInfoChanged invoked with wrong orientation.
Besides, if you just want to modify some control properties, you can use OrientationStateTrigger alternatively. About this, you can refer to Xamarin.Forms Visual State Manager.
And the following is a example that changing Label Text when Orientation changes.
<Label>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="OrientationStates">
<VisualState Name="Portrait">
<VisualState.StateTriggers>
<OrientationStateTrigger Orientation="Portrait" />
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Property="Text" Value="Portrait" />
</VisualState.Setters>
</VisualState>
<VisualState Name="Landscape">
<!--...-->
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Label>
Regards,
Kyle
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
9 people are following this question.