[英]Set C# file as startup file in Xamarin.Forms?
如何在 Xamarin 表單中將純 c# 文件設置為啟動文件? 我可以刪除MainPage.xaml
和MainPage.xaml.cs
並從ContentPage
文檔中添加以下代碼:
using System;
using Xamarin.Forms;
namespace ContentPageExample
{
public class App : Application
{
public static Page GetMainPage ()
{
return new ContentPage {
Content = new Label {
Text = "Hello, Forms!",
VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.CenterAndExpand,
},
};
}
public App ()
{
MainPage = GetMainPage();
}
}
}
如果將上述代碼添加到App.xaml.cs
,則可以正常工作。 但是如果我同時刪除App.xaml
和App.xaml.cs
,然后將上面的代碼添加到新文件App.cs
,則會出現錯誤
在 Android 項目的 MainActivity.cs 中找不到類型或命名空間名稱“App”(您是否缺少 using 指令或程序集引用?)。
我現在能想到的,這個問題可能出現的唯一方法是depecited代碼不是確切的代碼,在你的App.cs
,但你讓Visual Studio中添加到您的代碼添加一個新的類。
問題是,名為App
的類的 Visual Studio 的默認類模板是
using System;
using System.Collections.Generic;
using System.Text;
namespace ContentPageExample
{
class App
{
}
}
請注意,我們的類沒有訪問修飾符( public
、 internal
)。 但是對於類,默認的隱式訪問級別是internal
,即只有同一程序集中的類才能看到此類並創建1 的實例,因為MainActivity
位於另一個程序集中,因此不允許訪問App
。
您可以通過向App
添加顯式訪問修飾符來解決此問題
using System;
using System.Collections.Generic;
using System.Text;
namespace ContentPageExample
{
public class App
{
}
}
1有一個例外:您可以將InternalsVisibleToAttribute
添加到一個程序集以允許另一個程序集訪問內部類和方法,但我建議您很少使用它,並且絕對不要在當前情況下使用它。
您可以創建一個完整的 c# 文件作為 Xamarin 表單應用程序的啟動。 但請確保您的啟動類應從 Xamarin.Forms 的 Application 類派生。 因為它是跨平台應用程序的根頁面。 所以你的啟動類應該如下所示,
public class StartUp : Application
{
public StartUp()
{
// Set your main page here.
}
}
在 Android 中,MainActivity 類,
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new StartUp());
}
}
正如您提到的,您必須在應用程序啟動時設置一個新的 c# 文件,讓我們假設它為“Test.cs”。 在位於解決方案主項目中的 App.cs 文件的構造函數中,將新的 c# 文件“Test.cs”設置為應用程序的主頁面,並提及您使用的頁面類型(因為它可以是 ContentPage 或 NavigationPage) . 檢查以下示例代碼段。
public App()
{
InitializeComponent();
MainPage = new ContentPage (new Test());
}
如果您使用 MVVM 模式,那么您必須在 App.cs 文件的構造函數中使用 Class 文件注冊您的 ViewModel。 創建可以在頁面和 ViewModals、SetRoot()、彈出頁面和 ViewModels 之間導航的自定義 NavigationService。 然后覆蓋 App.cs 文件的 OnStart() 方法並為新的 c# 文件設置 SetRoot()。
public App()
{
InitializeComponent();
Instance = this;
MainPage = new ContentPage { Title = "Test" };
RegisterPages();
RegisterModals();
ModalPopping += ModalService.ModalPopping;
}
protected override void OnStart()
{
NavigationService.SetRoot(new Test());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.