C# 从mainviewmodel访问xaml控件
我在我的xaml windows phone应用程序中有地图控件,我想从我的mainviewmodel访问我的地图,因为我把所有逻辑代码都放在那里了,还有添加它的方法吗 地理位置= 等待geolocator.GetGeopositionAsync( 时间跨度从分钟(1), 时间跨度从秒(30)) 如果我把所有代码都放到mainpage.xaml.cs中,这就是应该存在的代码 myMap.SetView(gpsCenter,10) 这是我试图添加到我的xaml组件中的代码,它只进行一些缩放并将我的地图精确移动到手机位置数据,我可以将其放入mainpage.xaml.cs中,但由于我的mainviewmodel中需要两个变量(纬度和经度),所以我决定将其全部放入mainviewmodel中 编辑C# 从mainviewmodel访问xaml控件,c#,xaml,windows-phone-8,C#,Xaml,Windows Phone 8,我在我的xaml windows phone应用程序中有地图控件,我想从我的mainviewmodel访问我的地图,因为我把所有逻辑代码都放在那里了,还有添加它的方法吗 地理位置= 等待geolocator.GetGeopositionAsync( 时间跨度从分钟(1), 时间跨度从秒(30)) 如果我把所有代码都放到mainpage.xaml.cs中,这就是应该存在的代码 myMap.SetView(gpsCenter,10) 这是我试图添加到我的xaml组件中的代码,它只进行一些缩放并将我的
你不应该那样做。您的视图模型不应与视图直接交互。您应该在视图模型中创建一个可绑定的
geocordinate
属性,并将其绑定到Map.Center
属性
通过这种方式,您仍然可以清晰地分离UI和视图模型代码
--
编辑:将以下特性添加到视图模型中
GeoCoordinate _center;
public GeoCoordinate Center
{
get { return _center; }
set
{
_center = value;
OnPropertyChanged("Center"); // or whatever here
}
}
将
Map.Center
绑定到XAML中的该属性。如何创建可绑定的地理坐标?已经做了您要做的事情,但是得到了System.ArgumentNullException。知道为什么吗?因为默认情况下,Center
为null
。在构造函数中将其初始化为新地理坐标。我的意思是,错误说参数为空。嗯?对不起,我不明白。。。你能给我一些代码示例吗?Center=新地理坐标
。
private GeoCoordinate _center;
public GeoCoordinate center
{
get { return _center; }
set { this.SetProperty(ref this._center, value); }
}
public MainViewModel()
{
center = new GeoCoordinate();
}
private async void LoadTransportData()
{
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracyInMeters = 50;
Geoposition position =
await geolocator.GetGeopositionAsync(
TimeSpan.FromMinutes(1),
TimeSpan.FromSeconds(30));
center = new GeoCoordinate(
position.Coordinate.Latitude,
position.Coordinate.Longitude);
}
GeoCoordinate _center;
public GeoCoordinate Center
{
get { return _center; }
set
{
_center = value;
OnPropertyChanged("Center"); // or whatever here
}
}