我想使用命令将一些数据传递给服务,但我不想在代码中使用它。这就是我的尝试:
view.xaml.cs
ViewModel.FirstVm vm1;
public ViewPage(Models.Example example)
{
InitializeComponent();
NavigationPage.SetTitleIcon(this, "logosmall.png");
Tasks ts = new Tasks();
var myLocation = Task.Run(() =>
ts.GetDeviceCurrentLocation()).Result;
var latitudeIm = myLocation.Latitude;
var longitudeIm = myLocation.Longitude;
vm1 = new FirstVm(latitude, longitude, latitudeIm, longitudeIm);
routeInfo.Command = vm1.GetInfoCommand;
}
视图模型
public FirstVm(double latitude, double longitude, double latitudeIm, double longitudeIm)
{
this.latitude = latitude;
this.longitude = longitude;
this.latitudeIm = latitudeIm;
this.longitudeIm = longitudeIm;
}
public double latitude;
public double longitude;
public double latitudeIm;
public double longitudeIm;
public ICommand GetInfoCommand
{
get
{
return new Command(async () =>
{
// how to pass the parameters here
Routes = await _ts.GetRouteInfosAsync(latitude, longitude,latitudeIm,longitudeIm);
await Application.Current.MainPage.Navigation.PushAsync(new View(Routes));
});
}
}
tasks.cs
public async Task<List<Route>> GetRouteInfosAsync(double la, double lo, double laIm, double loIm)
{
var client = new HttpClient();
var json = await client.GetStringAsync("https://maps.googleapis.com/maps/api/directions/json?origin=31.320475 19.824573&destination=31.33765 11.87052&key=my_keyy");
var routes = JsonConvert.DeserializeObject<RootObject>(json);
return routes.routes;
}
我的做法是对的吗?!我做错了吗?谢谢:))
答案 0 :(得分:1)
您可以在Page:
的构造函数中编写BindingContext = YourViewModel()
ViewModel.FirstVm vm1;
public ViewPage(Models.Example example)
{
InitializeComponent();`
BindingContex = new YourViewModel(parameters)
NavigationPage.SetTitleIcon(this, "logosmall.png");
Tasks ts = new Tasks();
var myLocation = Task.Run(() =>
ts.GetDeviceCurrentLocation()).Result;
var latitudeIm = myLocation.Latitude;
var longitudeIm = myLocation.Longitude;
routeInfo.Command = vm1.GetInfoCommand;
routeInfo.CommandParameter = latitudeIm;
routeInfo.CommandParameter = longitudeIm;
routeInfo.CommandParameter = latitude;
routeInfo.CommandParameter = longitude;
}
然后在View模型中使用此参数创建构造函数并在命令
中使用它答案 1 :(得分:1)
您是否在构造方法FirstVm()
中设置了值?如果是这样,请先初始化您的虚拟机,然后再使用它。我猜你的构造应该是:
public FirstVm(double la, double lo, double laIm, double loIm)
{
latitude = la;
longitude = lo;
latitudeIm = laIm;
longitudeIm = loIm;
}
在ViewPage中,您应首先创建vm然后使用它:
vm1 = new FirstVm(latitude, longitude, latitudeIm, longitudeIm);
routeInfo.Command = vm1.GetInfoCommand;
或者您可以使用以下参数定义命令:
public ICommand GetInfoCommand
{
get
{
return new Command<List<double>>(async (List<double> list) =>
{
Routes = await _ts.GetRouteInfosAsync(list[0], list[1], list[2], list[3]);
await Application.Current.MainPage.Navigation.PushAsync(new View(Routes));
});
}
}
//use this command in ViewPage
routeInfo.CommandParameter = new List<double> { latitude, longitude, latitudeIm, longitudeIm };
请注意我们应该在使用之前先创建实例。