我正在使用 Xamarin 为 iOS 和 Android 创建一个应用程序,我有一个用例,我按下一个按钮,它会打开一个模态,然后在模态上选择一个按钮后,它会更新一些信息,然后我需要弹出模态并重新加载它下面的主页。这怎么可能?
主页:
public partial class MainPage : ContentPage
{
public MainPage(Object obj)
{
InitializeComponent();
// do some things with obj...
BindingContext = this;
}
public ButtonPressed(object sender, EventArgs args)
{
Navigation.PushModalAsync(new SecondaryPage(newObj));
}
}
第二页:
public partial class SecondaryPage : ContentPage
{
public SecondaryPage(Object newObj)
{
InitializeComponent();
BindingContext = this;
}
public ButtonPressed(object sender, EventArgs args)
{
// Do something to change newObj
Navigation.PopModalAsync();
}
}
所以在 PopModalAsync(( 之后,我需要能够调用 MainPage(( 构造函数,但将我在 secondaryPage 中更改的"newObj"传递给它。这可能吗?
在 .Net 中执行此操作的正确方法是设置一个事件:
public partial class SecondaryPage : ContentPage
{
public SecondaryPage(Object newObj)
{
InitializeComponent();
BindingContext = this;
}
// Add an event to notify when things are updated
public event EventHandler<EventArgs> OperationCompeleted;
public ButtonPressed(object sender, EventArgs args)
{
// Do something to change newObj
OperationCompleted?.Invoke(this, EventArgs.Empty);
Navigation.PopModalAsync();
}
}
public partial class MainPage : ContentPage
{
public MainPage(Object obj)
{
InitializeComponent();
// do some things with obj...
BindingContext = this;
}
public ButtonPressed(object sender, EventArgs args)
{
var secondaryPage = new SecondaryPage(newObj);
// Subscribe to the event when things are updated
secondaryPage.OperationCompeleted += SecondaryPage_OperationCompleted;
Navigation.PushModalAsync(secondaryPage);
}
private void SecondaryPage_OperationCompleted(object sender, EventArgs e)
{
// Unsubscribe to the event to prevent memory leak
(sender as SecondaryPage).OperationCompeleted -= SecondaryPage_OperationCompleted;
// Do something after change
}
}