从 ViewModel 绑定到 Xamarin.Forms.Maps.Map [英] Bind to Xamarin.Forms.Maps.Map from ViewModel

查看:28
本文介绍了从 ViewModel 绑定到 Xamarin.Forms.Maps.Map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用显示地图的页面开发 Xamarin.Forms 应用程序.XAML 是:

I'm working on a Xamarin.Forms app using a page that displays a map. The XAML is:

<maps:Map x:Name="Map">
    ...
</maps:Map>

我知道可以像这样从页面的代码隐藏中访问地图:

I know that the map can be accessed from the page's code-behind like this:

var position = new Position(37.79762, -122.40181);
Map.MoveToRegion(new MapSpan(position, 0.01, 0.01));
Map.Pins.Add(new Pin
{
    Label = "Xamarin",
    Position = position
});

但是因为这段代码会破坏应用程序的 MVVM 架构,所以我更愿意从我的 ViewModel 访问 Map 对象,而不是直接从视图/页面 - 或者像在以上代码或通过数据绑定到其属性.

But because this code would break the app's MVVM architecture, I'd rather like to access the Map object from my ViewModel, not directly from the View/page - either using it directly like in the above code or by databinding to its properties.

有人知道如何做到这一点吗?

Does anybody know a way how this can be done?

推荐答案

如果您不想打破 MVVM 模式并且仍然能够从 ViewModel 访问您的 Map 对象,那么您可以使用属性公开 Map 实例从您的 ViewModel 并从您的视图绑定到它.

If you don't want to break the MVVM pattern and still be able to access your Map object from the ViewModel then you can expose the Map instance with a property from your ViewModel and bind to it from your View.

您的代码的结构应如下所述.

Your code should be structured like described here below.

视图模型:

using Xamarin.Forms.Maps;

namespace YourApp.ViewModels
{
    public class MapViewModel
    {
        public MapViewModel()
        {
            Map = new Map();
        }

        public Map Map { get; private set; }
    }
}

视图(在本例中,我使用的是 ContentPage,但您可以使用任何您喜欢的内容):

The View (in this example I'm using a ContentPage but you can use whatever you like):

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="YourApp.Views.MapView">
    <ContentPage.Content>
                <!--The map-->
                <ContentView Content="{Binding Map}"/>
    </ContentPage.Content>
</ContentPage>

我没有展示怎么做,但是上面截取的代码只有在 ViewModel 是您的视图的 BindingContext 时才能工作.

I didn't show how, but the above code snipped can only work when the ViewModel is the BindingContext of your view.

这篇关于从 ViewModel 绑定到 Xamarin.Forms.Maps.Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆