我正在玩Xamarin Forms,我想以编程方式添加 Button . 没有比这更容易了,但我注意到如果按钮有 Image 而不是 Text ,结果会有很大差异 .

现在我有了这个XAML定义了一个三层屏幕( Headers ,内容,页脚):

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:Testing" 
             x:Class="Testing.MainPage"
             Title="MainPage"
             NavigationPage.HasNavigationBar="False">

    <ContentPage.Content>

        <!-- Content -->
        <StackLayout x:Name="contentpage" Padding="10,100,10,100">

            <!-- Header -->
            <StackLayout x:Name="header" Orientation="Horizontal" VerticalOptions="StartAndExpand">
                <Button Text="ABCD" VerticalOptions="Center" HorizontalOptions="StartAndExpand"/>        
                <Button Text="EFGH" VerticalOptions="StartAndExpand" HorizontalOptions="EndAndExpand"/>        
            </StackLayout>
            <!-- /Header -->


            <!-- Center -->    
            <StackLayout x:Name="content" Opacity="1" Orientation="Vertical" VerticalOptions="Start" >
                <Button x:Name="test" Text="Fire fire fire" HorizontalOptions="CenterAndExpand" VerticalOptions="Start" />
            </StackLayout>
            <!-- /Center -->


            <!-- Bottom -->    
            <StackLayout x:Name="buttons" Orientation="Horizontal" VerticalOptions="EndAndExpand">
                <Button Text="1" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"  />
                <Button Text="2" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"  />
                <Button Text="3" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"  />
                <Button Text="4" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"  />
                <Button Text="5" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"  />
            </StackLayout>
            <!-- /Bottom -->

        </StackLayout> <!-- Content -->

    </ContentPage.Content>

</ContentPage>

在相应的C#源代码中,我向 content 添加了一个按钮:

var custombutton = new Button();
custombutton.HorizontalOptions = LayoutOptions.CenterAndExpand;
custombutton.VerticalOptions = LayoutOptions.Start;
custombutton.Image = "mountain.jpg";
//custombutton.Text = "hello";


content.Children.Add(
    custombutton
);

如您所见,我想通过设置图像来更改按钮的属性,但布局会发生显着变化 .

results

正如你所看到的,如果我添加带有文本的按钮,那么按钮似乎不服从它的垂直选项(右),或者它增加了一些奇怪的填充 . 当然我只想添加带有文本或图像的按钮而不会丢失页脚 StackLayout ,但我不会在这里发生 .

我在这里错过了什么吗?

尺寸更新

正如所建议的那样,我尝试了不同的布局,但最终我得到了相同的结果 . 最后一次测试是 Grid ,而 ScrollView 内部是 StackLayout . 不同的观点和安排不会改变我的项目中的任何内容 .

重要的是 the image size ,你可以看到:

size-tests

此处的图像大小为 1668 × 796355 × 190 像素 .

A fully functional source is here available for downloadlink to the solution .

控制更新

无论图像大小如何,使用 Image 都可以完美地工作 . 不知道为什么 Button 会增加依赖于图像的巨大空间 .