Home > database >  Xamarin.Forms: add control (in XAML) based on Platform
Xamarin.Forms: add control (in XAML) based on Platform

Time:05-03

I have this (simplified) layout in XAML using Xamarin Forms:

<controls:MyTabItemView>
    <ScrollView>
        <Grid>
            ......
                <controls:CustomButton x:Name="XYZ"/>
            ......
        </Grid>
    </ScrollView>
</controls:TabItemView>

This is fine in iOS, but in Android, I do NOT want the ScrollView, the main container should be the Grid, so like:

<controls:MyTabItemView>
    <Grid>
         ......
            <controls:CustomButton x:Name="XYZ"/>
         ......
    </Grid>
</controls:TabItemView>

If I try to create 2 layout using the <OnPlatform> and <On Platform="Android" / "iOS"> paradigm (basically duplicate all in XAML, but remove the <ScrollView> in the Android part), that almost works, but due to XYZ it will result in build error, as the .g.cs file will declare the XYZ twice. This is a known error, see: Xamarin OnPlatform - Duplicate Names

So as I could not do in XAML, I tried to hack in xaml.cs, in the view constructor,

if (Xamarin.Forms.Device.RuntimePlatform == Xamarin.Forms.Device.Android)
{
    Children[0] = Children[0].Children[0];  //get rid of ScrollView
}

This won't compile as Children is IReadOnlyList.

Any suggestion, what is the best solution here, to NOT add the ScrollView in case of Android, but start with the Grid as the main container?

Thanks

CodePudding user response:

Since you know the layout that was created, after InitializeComponent(); you can do the replacement this way:

var topLayout = (ScrollView)Children[0];
Children.RemoveAt(0);
Children.Insert(0, topLayout.Children[0]);

This replaces the ScrollView with its first child.

  • Related