如何从后端访问 StackLayout?

How to access StackLayout from the backend?

我一直在使用 Xamarin Forms 开发 iOS 和 Android 应用程序。我想访问 TabbedPage 中的 StackLayout,这样我就可以在用户更改选项卡时使其可见或隐藏,但是当我尝试访问 StackLayout 时,我得到 "This does not exist in the current context"。这是我的 XAML 代码和我的 CS 代码。

CS

using System;
using System.Collections.Generic;
using Xamarin.Forms;

namespace DebuggerTestAndroidIOS
{
    public partial class PatientTabPage : TabbedPage
    {
        public PatientTabPage ()
        {
            InitializeComponent ();
            ItemsSource = PatientDataModel.tabs;
            //vitalSignsStack.IsVisible = true;

            this.CurrentPageChanged += (object sender, EventArgs e) => {
                var i = this.Children.IndexOf(this.CurrentPage);
                System.Diagnostics.Debug.WriteLine("Page No:"+i);

                if (i == 1){
                    vitalSignsStack.IsVisible = true;
                }           
            };
        }
    }
}

XAML

<?xml version="1.0" encoding="UTF-8"?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            x:Class="DebuggerTestAndroidIOS.PatientTabPage">
    <TabbedPage.ItemTemplate>
        <DataTemplate>
            <ContentPage Title ="{Binding TabName}">
                <!--Parent Wrapper layout-->
                <StackLayout Orientation="Vertical" BackgroundColor="White">
                   <StackLayout x:Name="vitalSignsStack" Orientation="Horizontal" IsVisible="false">
                        <Image Source="VitalSigns.png" HorizontalOptions="Center"/>
                    </StackLayout>
                </StackLayout><!--End parent wrapper-->
            </ContentPage>
        </DataTemplate>
    </TabbedPage.ItemTemplate>
</TabbedPage>

元素只能在创建它的页面的上下文中访问 - 在本例中为 ContentPage。

如果您想从 ContentPage 外部访问它,您需要添加一个 public 方法或 属性 到公开它的 ContentPage。

您无法使用其名称访问 DataTemplate 内的控件。问题是,它会被重复,所以这个名字会出现多次,这是不允许的。

但是你为什么不像这样创建一个新页面:

public partial class PatientTabContentPage : TabbedPage
{
    public PatientTabContentPage ()
    {
        InitializeComponent ();
    }
    public HideVitalSignsStack(bool true){
        vitalSignsStack.IsVisible = true;
    }
}

并将 DataTemplate 更改为

<DataTemplate>
    <PatientTabContentPage Title ="{Binding TabName}">
</DataTemplate>

然后用

隐藏堆栈面板
this.CurrentPageChanged += (object sender, EventArgs e) => {
    var page = CurrentPage as PatientTabContentPage;
    var i = this.Children.IndexOf(this.CurrentPage);
    System.Diagnostics.Debug.WriteLine("Page No:"+i);    
    if (i == 1){
        page.HideVvitalSignsStack(true);
    }   
};

感谢您的努力。我试过了,仍然无法访问 StackLayouts。我稍微修改了我的代码,这很有帮助,让一切变得更容易:Creating different layouts for each tab