【问题标题】:Xamarin - get control dimensionsXamarin - 获取控制尺寸
【发布时间】:2022-01-09 05:37:19
【问题描述】:

我真的不知道如何在 Xamarin Forms 中获取控件尺寸。我认为这很容易:

View control = GetControlSomehow();
var bounds = control.Bounds;

但是 View.Bounds 会根据控件是否在网格内返回不同的内容;或者主布局是 AbsoluteLayout 还是其他布局。

例如,如果我执行以下操作:

<AbsoluteLayout>
    <Button AbsoluteLayout.LayoutBounds="200,200" x:Name="btn" Text="Btn"/>
</AbsoluteLayout>

然后我无法读取该按钮的实际高度或宽度。虽然 MSDN 说 Height 和 Width 属性应该返回这些值。

我什至尝试过:

var width = ctrl.Width;

var width = ctrl.GetValue(WidthProperty);

但实际上这些都不起作用。我总是得到-1

那么我怎样才能得到可能可靠的控制维度呢?

【问题讨论】:

  • 您是如何读取高度和宽度的?您是否要等到布局完成后再尝试?
  • 全部加载完毕。例如,当我的页面出现时,我单击某个按钮,然后想要获取尺寸
  • 为了帮助以后遇到类似问题的其他人,请在您的问题中添加不起作用的代码。然后这变成了一个完整的问答,展示了哪些不起作用,并显示了有关其他解决方法的答案。

标签: xamarin.forms


【解决方案1】:

这对我有用

<Button Text="Click" Clicked="Clicked"  />

public void Clicked(object sender, EventArgs a)
    {
        var btn = (Button)sender;

        var w = btn.Width;
        var h = btn.Height;

        DisplayAlert("Dimesions", $"{w}x{h}","OK");

    }

【讨论】:

  • 这不行,我只得到-1
  • @AdamJachocki - 请将无效代码添加到问题。我已经确认 Jason 的回答在 Android 和 UWP 上都有效。因此,问题在于您如何使用它。注意:“-1”表示您正在测试一个尚未布局的视图。 (这发生在它在屏幕上可见之前。)不知何故,您指的不是屏幕上可见的实际按钮。或者您指的是它在可见之前所具有的值。或者 XAML 中还有一些您没有显示的内容。
【解决方案2】:

显示如何使用数据绑定传递按钮本身的完整示例。

AbsoluteLayoutPage.xaml:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TestBugs.AbsoluteLayoutPage">
    <ContentPage.Content>
        <AbsoluteLayout>
            <Button AbsoluteLayout.LayoutBounds="200,200" x:Name="btn" Text="Btn"
                    Command="{Binding ButtonCommand}" CommandParameter="{x:Reference btn}"/>
        </AbsoluteLayout>
    </ContentPage.Content>
</ContentPage>

AbsoluteLayoutPage.xaml.cs:

using System.Diagnostics;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace TestBugs
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class AbsoluteLayoutPage : ContentPage
    {
        public AbsoluteLayoutPage()
        {
            ButtonCommand = new Command(ButtonClick);
            InitializeComponent();
            BindingContext = this;
        }

        private void ButtonClick(object ob)
        {
            var button = ob as View;
            var bounds = btn.Bounds;
            var width = btn.Width;
            var height = btn.Height;
            Debug.WriteLine($"--- ButtonClick {bounds}, ({width},{height})---");

        }

        public Command ButtonCommand { get; set; }
    }
}

单击按钮时,在 VS 输出窗格中:

[0:] --- ButtonClick {X=200 Y=200 Width=88 Height=48}, (88,48)---

【讨论】:

    【解决方案3】:

    对不起各位,我的错。 我在两页上测试它——真实的一页和测试的一页。测试页面以不同的方式构建,我确认问题是在我检索这些值时及时出现的。控件尚未绘制。

    因此,非常抱歉打扰您,并感谢大家为此投入时间。

    【讨论】:

    • 没问题 - 它发生在我们所有人身上。很高兴你把它解决了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多