【发布时间】:2020-03-10 17:58:27
【问题描述】:
我是 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, new Rectangle(0.5, 0.2, 200, 100));
var bottone2 = new Button { Text = "Start222" };
container1.Children.Add(bottone2);
AbsoluteLayout.SetLayoutBounds(bottone2, new Rectangle(0.5, 0.2, 200, 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,不知道为什么,这是什么意思。
【问题讨论】:
-
如果你想控制元素的定位,那么不要使用 StackLayout
-
@Jason 那我该用什么?除了那个建议为什么它不起作用?为什么 WidthRequest 两者都没有?
-
任何其他布局 - Grid、AbsoluteLayout、RelativeLayout 等
-
@Jason 刚刚尝试了 AbsoluteLayout 并给了我同样的问题,命令不起作用,现在一切都设置在屏幕的左上角
标签: c# xaml xamarin layout xamarin.forms