如何导航后调用异步web方法完成
本文关键字:web 异步 方法 调用 何导航 导航 | 更新日期: 2023-09-27 17:53:50
我正在开发一个使用webservice的windows phone应用程序。
我想在完成webmethod调用后导航到另一个页面。我不知道这怎么可能。
这是我的视图后台代码的一部分:
private void Button1Button_Click(object sender, RoutedEventArgs e) { this._ws.InitializeConnexion("my name"); this.NavigationService.Navigate(new Uri("/View/profile.xaml", UriKind.Relative)); }
这是我的视图模型类:
public sealed class MobileViewModel : INotifyPropertyChanged { private WSClient _ws; private T_member _member; public T_member Member { get { return _member; } set { _member = value; this.RaisePropertyChanged("Member"); } } public MobileViewModel() { _ws = new WSMobileClient(); _ws.InitializeConnexionCompleted += new EventHandler<InitializeConnexionCompletedEventArgs>(_ws_InitializeConnexionCompleted); } public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public void InitializeConnexion(string name) { _ws.InitializeConnexionAsync(name); } private void _ws_InitializeConnexionCompleted(object sender, InitializeConnexionCompletedEventArgs e) { if (e.Error == null) { this.Member = e.Result; } else { MessageBox.Show("error."); } } }
有人能帮我吗?
谢谢。
我会向触发web方法调用的方法传递一个continuation lambda -然后在调用成功完成时执行continuation:
private void Button1Button_Click(object sender, RoutedEventArgs e)
{
InitializeConnexion("my name", () =>
{
this.NavigationService.Navigate(new Uri("/View/profile.xaml", UriKind.Relative));
});
}
您可以将其存储为MobileViewModel
类中的Action
。
Action _webCallCompletedAction;
public void InitializeConnexion(string name, Action action)
{
webCallCompletedAction = action;
_ws.InitializeConnexionAsync(name);
}
,最后在web服务全部完成后执行:
private void _ws_InitializeConnexionCompleted(object sender,
InitializeConnexionCompletedEventArgs e)
{
if (e.Error != null)
{
this.Member = e.Result;
webCallCompletedAction();
}
else
{
MessageBox.Show("error.");
}
}
}
您当然可以这样做。几个建议:
1)使用iccommand并将其绑定到按钮而不是后面的代码。这就把逻辑放到了它所属的视图模型中。这里有一个如何做到这一点的例子。和另一个。
2)一旦你在视图模型中有了那个逻辑,那么你就可以用你的连接状态编排导航,而不需要将消息传递回视图。比如:
private void _ws_InitializeConnexionCompleted(object sender, InitializeConnexionCompletedEventArgs e)
{
if (e.Error != null)
{
this.Member = e.Result;
this.Navigate("/View/profile.xaml");
}
else
{
MessageBox.Show("error.");
}
}
}
protected void Navigate(string address)
{
if (string.IsNullOrEmpty(address))
return;
Uri uri = new Uri(address, UriKind.Relative);
Debug.Assert(App.Current.RootVisual is PhoneApplicationFrame);
((PhoneApplicationFrame)App.Current.RootVisual).Navigate(uri);
}