大家好:我的代码卡在这里了。我的应用程序中有一个地方需要通知用户进行注册和签名,以保存他们的偏好。我一直试图在ViewModel内添加显示警报,但是它不起作用。请帮助我被卡住。
ApproveViewModel
namespace MyApp.ViewModels
{
public class ApproveViewModel
{
private DataService dataService = new DataService();
public Oppotunity SelectedOppotunity { get; set; }
public ICommand SaveCommand => new Command(async () =>
{
await dataService.PostSaveOppotunity(SelectedOppotunity, Settings.AccessToken);
});
public ApproveViewModel()
{
SelectedOppotunity = new Oppotunity();
}
}
}
ApprovePage.xaml
<ScrollView>
<StackLayout Padding ="15">
<Label Text ="{Binding SelectedOppotunity.Title}"/>
<Label Text ="{Binding SelectedOppotunity.Description }"/>
<Label Text ="{Binding SelectedOppotunity.Organisation}"/>
<Label Text ="{Binding SelectedOppotunity.Venue }"/>
<Label Text ="{Binding SelectedOppotunity.Eligibility}"/>
<Label Text ="{Binding SelectedOppotunity.Benefits}"/>
<Label Text ="{Binding SelectedOppotunity.Province}"/>
<Label Text ="{Binding SelectedOppotunity.Country}"/>
<Label Text ="{Binding SelectedOppotunity.OppotunityLink}"/>
<Label Text ="{Binding SelectedOppotunity.Category}"/>
<Label Text ="{Binding SelectedOppotunity.Deadline}"/>
<!--
<Switch IsToggled ="{Binding SelectedOppotunity.IsApproved}"></Switch>
-->
<Button Text ="Apply" BackgroundColor ="#A91717" TextColor ="White"
Command ="{Binding SaveCommand }"/>
</StackLayout>
我希望在保存时调用的代码:
if (!string.IsNullOrEmpty(Settings.AccessToken))
{
// Implement the SaveCommand from the ViewModel;
}
// Go to Login form to get an access token
else if (!string.IsNullOrEmpty(Settings.Username) &&
!string.IsNullOrEmpty(Settings.Password))
{
MainPage = new NavigationPage(new Login());
}
else
{
//Register first
MainPage = new NavigationPage(new NewRegisterPage());
}
答案 0 :(得分:0)
如果您不想从ViewModel中显示警报,则可以:
Application.Current.MainPage.DisplayAlert();
答案 1 :(得分:0)
解决方案:
您可以使用MessageCenter
订阅来解决此问题。
Xamarin.Forms MessagingCenter 启用视图模型和其他组件 交流而不必彼此了解 除了简单的消息合同。
订阅-收听具有特定签名的邮件并执行 收到通知后采取一些措施。可以有多个订阅者 收听相同的消息。
发送-发布消息,供听众采取行动。如果不 侦听者已订阅,则该消息将被忽略。
视图模型中的代码:
if (!string.IsNullOrEmpty(Settings.AccessToken))
{
// Implement the SaveCommand from the ViewModel;
}
// Go to Login form to get an access token
else if (!string.IsNullOrEmpty(Settings.Username) &&
!string.IsNullOrEmpty(Settings.Password))
{
MainPage = new NavigationPage(new Login());
}
else
{
//Register first
//if you want to notify users to register here, use MessageCenter.Send
MessageCenter.Send(this, "displayAlert")
MainPage = new NavigationPage(new NewRegisterPage());
}
视图中的代码:
MessagingCenter.Subscribe<ViewModelName>(this, "displayAlert", (sender) => {
// do something whenever the "displayAlert" message is sent
DisplayAlert("notification", "you should register first", "ok");
});
将消息发送到要在viewModel中显示警报的位置。
有关MessageCenter的更多信息,您可以参考https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/messaging-center