如何获得MvvmCross MKAnnotation实时更新绑定

时间:2014-11-05 18:22:20

标签: xamarin.ios xamarin mapkit mvvmcross mvxbind

我试图在Xamarin iOS项目中实时更新MKMapKit注释。

我正在使用MvvmCross,并以@slodge代码的实现为基础,并且它运作良好。

https://gist.github.com/slodge/6070386

我现在能够做的就是斯图尔特在其中一条评论中提到的内容。

public class HouseAnnotation : MKAnnotation
{
    public HouseAnnotation(House house)
    {
        // use house here... 
        // in theory you could also data-bind to the house too (e.g. if it's location were to move...)
    }

    public override CLLocationCoordinate2D Coordinate { get; set; }
}

我如何将House坐标绑定到HouseAnnotation.Coordinate

到目前为止,我一直在做绑定:

var bindingSet = this.CreateBindingSet<View, ViewModel>();

直接在viewDidLoad中执行此操作,并且可以访问您需要的所有内容。

我觉得我自然想做

var bindingSet = myView.CreateBindingSet<HouseAnnotation, House>();

但这意味着将对myView的引用传递给HouseAnnotation,因此可以用它来调用CreateBindingSet,我怀疑这甚至可以工作,因为House和HouseAnnotation不是子类任何Mvx基类。

我觉得我在这里错过了一些难题。有人能帮助我吗?

我知道房子不太可能移动,但我正在为所有可能性做好准备!

1 个答案:

答案 0 :(得分:1)

您可以使用WeakSubscribe

订阅house.Location属性的更改

答案是在大约24分钟时的n + 38。

https://www.youtube.com/watch?v=JtXXmS3oHHY

public class HouseAnnotation : MKAnnotation
{
    private House _house;

    public HouseAnnotation(House house)
    {
        // Create a local reference
        _house = house;
        // We update now so the annotation Coordinate is set first time round
        UpdateLocation()
        // Subscribe to be notified of changes to the Location property to trigger the UpdateLocation method
        _house.WeakSubscribe<House>("Location", (s, e) => UpdateLocation());
    }

    private void UpdateLocation()
    {
        // Convert our house.Location to a CLLocationCoordinate2D and set it on the MKAnnotation.Coordinate property
        Coordinate = new CLLocationCoordinate2D(_house.Location.Lat, _house.Location.Lng);
    }

    public override CLLocationCoordinate2D Coordinate {
        get {
            return coord;
        }
        set {
            // call WillChangeValue and DidChangeValue to use KVO with
            // an MKAnnotation so that setting the coordinate on the
            // annotation instance causes the associated annotation
            // view to move to the new location.

            // We animate it as well for a smooth transition
            UIView.Animate(0.25, () => 
                {
                        WillChangeValue ("coordinate");
                        coord = value;
                        DidChangeValue ("coordinate");
                });
        }
    }
}