我是Xamarin的初学者,我试图学习制作简单的图形元素,例如按钮和图像。我的问题是,当我尝试更改元素的尺寸或位置(在示例中为按钮)时,似乎什么都没有改变。
我已经尝试过类似startButton.WidthRequest = 300;
或使用绝对布局AbsoluteLayout.SetLayoutBounds(startButton,new Rectangle(0.5,0.2,200,100));
之类的方法,但是没有任何效果,并且在模拟器中的应用程序中,所有内容似乎都在屏幕底部设置了默认高度和宽度屏幕上的。
XAML(也尝试过<AbsoluteLayout>
,但遇到了同样的问题,所有内容都设置在屏幕的左上角,并且setLayoutBounds或WidthRequest无效)
<?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:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:local="clr-namespace:TestImages;assembly=TestImages"
x:Class="TestImages.MainPage">
<StackLayout x:Name="container1">
<!-- Place new controls here -->
<Label Text="Welcome to MyApp" HorizontalOptions="Center" VerticalOptions="StartAndExpand" />
<Image Source="{local:ImageResource TestImages.kids2.png}"/>
<Button x:Name="startButton"
Text="START"
Clicked="goToList" />
</StackLayout>
</Contenpage>
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Essentials;
using Xamarin.Forms;
namespace TestImages
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
var mainDisplayInfo = DeviceDisplay.MainDisplayInfo;
var screenWidth = mainDisplayInfo.Width;
Console.WriteLine($"Width: {screenWidth}");
startButton.BackgroundColor = Color.LightGreen;
startButton.BorderColor = Color.White;
startButton.CornerRadius = 8;
startButton.BorderWidth = 1.5;
startButton.WidthRequest = 300;
AbsoluteLayout.SetLayoutBounds(startButton,100));
var bottone2 = new Button { Text = "Start222" };
container1.Children.Add(bottone2);
AbsoluteLayout.SetLayoutBounds(bottone2,100));
bottone2.BackgroundColor = Color.Beige;
Console.WriteLine($"Button: {startButton.Width}");
}
async void goToList(object sender,EventArgs e)
{
System.Diagnostics.Debug.Write("Cliccato START");
Console.Write("Cliccato START");
await Navigation.PushAsync(new ListPage());
}
}
}
我让它打印调试的按钮宽度,它说它是= -1,不知道为什么,这是什么意思。