我正在使用Page
开始新的Activator.CreateInstance
private void OnMenuSelected(object sender, SelectedItemChangedEventArgs e)
{
if (item.Title == "Movies")
{
//Type page = (MasterPageItem)e.SelectedItem.TargetType;
//page is HomePage
Detail = new NavigationPage((Page)Activator.CreateInstance(page));
}
}
HomePage.xaml.cs
public partial class HomePage : TabbedPage
{
public string MenuName { get; set; }
public HomePage()
{
InitializeComponent();
//if (MenuName == "Movies")
//this.CurrentPage = Children[1];
}
}
我想从Activator.CreateInstance
到MenuName
发送数据,我该怎么做?
由于this问题,我无法使用constructor
。
答案 0 :(得分:2)
为什么在实例化HomePage之后不能只设置MenuName属性(它是公共的)?例如:
private void OnMenuSelected(object sender, SelectedItemChangedEventArgs e)
{
if (item.Title == "Movies")
{
Type page = (MasterPageItem)e.SelectedItem.TargetType;
//page is HomePage
var pageInstance = (HomePage)Activator.CreateInstance(page)
pageInstance.MenuName = item.Title;
Detail = new NavigationPage(pageInstance);
}
}
如果那行不通,请解释原因?
编辑(在获得测试项目之后):
创建HomePage实例后,您要设置MenuName:
if (item.Title == "Movies")
{
Type page = item.TargetType;
var pageInstance = (HomePage)Activator.CreateInstance(page);
// So now you already have your HomePage and you already checked
// in HomePage constructor for the value of MenuName, but it has
// not been set yet, as it is set on the next line:
pageInstance.MenuName = item.Title;
Detail = new NavigationPage(pageInstance);
IsPresented = false;
}
但要在HomePage构造函数中检查MenuName的值,即在设置菜单名称之前:
public HomePage()
{
InitializeComponent();
if (MenuName == "Movies")
{
this.CurrentPage = Children[1];
}
}
也许可以在OnAppearing替代项中检查MenuName:
public partial class HomePage : TabbedPage
{
public string MenuName { get; set; }
public HomePage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
if (MenuName == "Movies")
{
this.CurrentPage = Children[1];
}
}
}
以上似乎按预期工作。
答案 1 :(得分:1)
我建议使用虚拟方法Initialize()
创建从TabbedPage插入的基础页面
public class MyTabbedPage : TabbedPage
{
public virtual void Initialize(object parameters)
{
}
}
然后您可以使用:
private void OnMenuSelected(object sender, SelectedItemChangedEventArgs e)
{
//Type page = (MasterPageItem)e.SelectedItem.TargetType;
//page is HomePage
var page = (Page) Activator.CreateInstance(page);
Detail = new NavigationPage(page);
if (page is MyTabbedPage tabbedPage)
tabbedPage.Initialize(params);
}
public partial class HomePage : MyTabbedPage
{
public string MenuName { get; set; }
public HomePage()
{
InitializeComponent();
//if (MenuName == "Movies")
//this.CurrentPage = Children[1];
}
public override void Initialize(object parameters)
{
//Stuff
}
}
也将XAML端也更改为MyTabbedPage
答案 2 :(得分:0)
编辑:也许不是最好的主意...
使用Activator.CreateInstance
。您可以执行以下操作:
private void OnMenuSelected(object sender, CustomArgstype args)
{
var parameter = args.MenuName;
if (parameter != null)
{
page = (Page)Activator.CreateInstance(type, parameter);
}
else
{
page = (Page)Activator.CreateInstance(type);
}
}