Forum Libraries, Components, and Plugins

VisualStateManager - Change Grid/RowDefinitions in XAML


i have a simple Grid Layout (1 Column with 100% width and 2 Rows with 50% height for each row). Now i want to change this Layout to 1 Row with 100% Height and 2 Columns (with 50% width for each column) if the device is in landscape mode.

Can i define this directly in XAML (with VisualStateManager)? I saw a sample for UWP which uses the "Target" Property of the Setter Item (VisualState.Setters/Setter), but in Xamarin Forms i can only use the "Property" Property.

Currently i'm defining this behavior directly in the code behind file.


<Grid x:Name="mainGrid" BackgroundColor="Bisque" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
        <RowDefinition Height="*"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
        <ColumnDefinition Width="*"></ColumnDefinition>
        <ColumnDefinition Width="0"></ColumnDefinition>

    <Label x:Name="Label1" Grid.Row="0" Grid.Column="0" BackgroundColor="Accent"/>
    <Label x:Name="Label2" Grid.Row="1" Grid.Column="0" BackgroundColor="Aqua"/>

Code Behind

        SizeChanged += (sender, args) =>
            bool portrait = Height > Width;
            if (portrait)
                mainGrid.ColumnDefinitions[1].Width = new GridLength(0);
                mainGrid.RowDefinitions[1].Height = GridLength.Star;
                Grid.SetColumn(Label2, 0);
                Grid.SetRow(Label2, 1);
                mainGrid.ColumnDefinitions[1].Width = GridLength.Star;
                mainGrid.RowDefinitions[1].Height = new GridLength(0);
                Grid.SetColumn(Label2, 1);
                Grid.SetRow(Label2, 0);

Thanks Thomas


Sign In or Register to comment.