【问题标题】:MVVMCross Field Binding CodeBehindMVVM 跨字段绑定 CodeBehind
【发布时间】:2019-02-20 06:32:44
【问题描述】:

我正在尝试使用 GoogleMaps nuget 包将 MapLongClicked 事件的 EventArgs 结果绑定到 Xamarin Forms 上的 ViewModel 上的属性“Location”。 问题是我只能在后面的 XAML 代码中访问那些 EventArgs。 当我使用 MVVMCross 时,我发现 something 关于字段绑定,但它不适用于后面的代码。 我的 MapPage 现在看起来像这样:

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MapPage : MvxContentPage
{
    public MapPage()
    {
        InitializeComponent();

        map.UiSettings.ZoomControlsEnabled = false;

        map.MapLongClicked += (sender, e) =>
        {
            //((MapViewModel)map.BindingContext).Location = new Microsoft.Azure.Documents.Spatial.Point(e.Point.Longitude, e.Point.Latitude);
            var pin = new Pin
            {
                Type = PinType.SearchResult,
                Position = new Position(e.Point.Latitude, e.Point.Longitude),
                Label = string.Format(e.Point.Latitude.ToString("0.000") + " / " + e.Point.Longitude.ToString("0.000"))
            };
            map.Pins.Add(pin);
        };

    }
}

XAML:

<mvx:MvxContentPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:mvx="clr-namespace:MvvmCross.Forms.Views;assembly=MvvmCross.Forms"
    xmlns:maps="clr-namespace:Xamarin.Forms.GoogleMaps;assembly=Xamarin.Forms.GoogleMaps"
    xmlns:behaviors="clr-namespace:XamFormsMaps.Core.Behaviors;assembly=XamFormsMaps.Core"
    x:Class="XamFormsMaps.Core.Pages.MapPage">
    <ContentPage.Content>
        <StackLayout>
            <maps:Map 
               x:Name="map"
               WidthRequest="320" 
               HeightRequest="200"
               IsShowingUser="true"
               MapType="Hybrid">

                <maps:Map.Behaviors>
                    <behaviors:MapBehavior ItemsSource="{Binding Parkings}" />
                </maps:Map.Behaviors>
            </maps:Map>
        </StackLayout>
    </ContentPage.Content>
</mvx:MvxContentPage>

我已经尝试了注释选项,但它给了我一个投射错误,所以我没有更多的想法。

有谁知道如何将 XAML 代码中的变量发送到 ViewModel?

【问题讨论】:

  • 地图在 XAML 上是否有 MapLongClicked 属性?
  • 耶!它确实@FabriBertani
  • 您是否尝试将该属性与视图模型上的命令绑定?喜欢MapLongClick="{Binding SomeCommand}"
  • 我试过了,但我不知道如何从 ViewModel 上的该命令获取 EventArgs 是否可行
  • 因为map.bindingcontext 不是MapViewModel,所以出现转换错误?

标签: c# xamarin.forms mvvmcross


【解决方案1】:

这解决了我的问题:

((MapViewModel)map.BindingContext).Location = new Microsoft.Azure.Documents.Spatial.Point(e.Point.Longitude, e.Point.Latitude);
        var pin = new Pin

确保 map.BindingContext 在运行时是 MapViewModel。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多