簡體   English   中英

如何在 C# 中命名 ContentPage?

[英]How to name a ContentPage in C#?

在 XAML 中,您將ContentPage命名如下:

<ContentPage ........
             x:Name="ThisPage">
</ContentPage>

如何在 C# 中執行此操作? 我似乎找不到任何關於它的參考。

取決於上下文您如何使用它,以及您使用它的目的,假設您有一個ContentPage

YourPage.xaml

<ContentPage x:Class="YourNameSpace.YourPage"
....

YourPage.xaml.cs

namespace YourNameSpace
{
    public partial class YourPage : ContentPage
    {
        public YourPage()
        {
            InitializeComponent();
        }
    }
}

這是一個示例,具體取決於您如何使用它(實例化它):

從 xaml

App.xaml

...
    <Application.MainPage>
        <YourNameSpace:YourPage x:Name="ThisPage"/>
    </Application.MainPage>

筆記

這部分真正生成的代碼可以在您的obj/文件夾中找到,擴展名為*.xaml.g.cs ,“g”代表“生成”:

public partial class App : Application
    {
        private global::YourNameSpace.YourPage ThisPage;
    }

 private void InitializeComponent() {
            global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(App));
            ThisPage= global::Xamarin.Forms.NameScopeExtensions.FindByName<global::YourNameSpace.YourPage>(this, "ThisPage");
        }

從代碼

在大多數使用情況下,天氣在 xaml 或代碼中,目標只是在實例化后訪問頁面的引用。

App.xaml.cs

作為變量:

    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
            var ThisPage = new YourPage();
            MainPage = ThisPage;
           //ThisPage.DoSomething
        }
    }

或作為 class 字段:

App.xaml.cs

    public partial class App : Application
    {
        YourPage ThisPage = new ThisPage();
        public App()
        {
            InitializeComponent();
            MainPage = ThisPage;

           //ThisPage.DoSomething
        }

        void Method()
        {
             ...
             //ThisPage.DoSomething
        }
    }

你命名它就像你命名任何 C# object

var ThisPage = new ContentPage();

ThisPage是對您的元素的引用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM