Xamarin C# - 列表中的对象<>自动更新自己,如何更新列表?

时间:2016-11-03 04:45:28

标签: c# list xamarin.forms

我正致力于my Github repository的xamarin解决方案。对于Pins project,我遇到了问题。有一件事,如果您创建一个引脚(又名CustomPin()),然后,您想要编辑该位置。然后,如果更改地址,地址名称将更改并且位置相同,将根据地址名称创建位置。所以从这里开始,这很容易。

但是,当Pin地址/位置发生变化时,我希望我的Map更新本身。但是因为List<>属性不会更改,也不会更新地图。

那么,获取指向父列表或地图的指针?

但是这个解决方案似乎不适合我的使用,我想也许,另一个最好的解决方案存在,但我不知道该怎么办..

您可以编译项目,但有三个更新。

CustomPin

public class CustomPin : BindableObject
{
    public static readonly BindableProperty AddressProperty =
        BindableProperty.Create(nameof(Address), typeof(string), typeof(CustomPin), "",
            propertyChanged: OnAddressPropertyChanged);
    public string Address
    {
        get { return (string)GetValue(AddressProperty); }
        set { SetValue(AddressProperty, value); }
    }
    private static async void OnAddressPropertyChanged(BindableObject bindable, object oldValue, object newValue)
    {
        (bindable as CustomPin).SetValue(LocationProperty, await CustomMap.GetAddressPosition(newValue as string));

    }

    public static readonly BindableProperty LocationProperty =
      BindableProperty.Create(nameof(Location), typeof(Position), typeof(CustomPin), new Position(),
          propertyChanged: OnLocationPropertyChanged);
    public Position Location
    {
        get { return (Position)GetValue(LocationProperty); }
        set { SetValue(LocationProperty, value); }
    }
    private static async void OnLocationPropertyChanged(BindableObject bindable, object oldValue, object newValue)
    {
        (bindable as CustomPin).SetValue(AddressProperty, await CustomMap.GetAddressName((Position)newValue));
        Debug.WriteLine("private static async void OnLocationPropertyChanged(BindableObject bindable, object oldValue, object newValue)");
    }

    public string Name { get; set; }
    public string Details { get; set; }
    public string ImagePath { get; set; }
    public uint PinSize { get; set; }
    public uint PinZoomVisibilityMinimumLimit { get; set; }
    public uint PinZoomVisibilityMaximumLimit { get; set; }
    public Point AnchorPoint { get; set; }
    public Action<CustomPin> PinClickedCallback { get; set; }

    public CustomPin(Position location)
    {
        Location = location;
        Name = "";
        Details = "";
        ImagePath = "";
        PinSize = 50;
        PinZoomVisibilityMinimumLimit = uint.MinValue;
        PinZoomVisibilityMaximumLimit = uint.MaxValue;
        AnchorPoint = new Point(0.5, 1);
        PinClickedCallback = null;
    }
    public CustomPin(string address)
    {
        Address = address;
        Name = "";
        Details = "";
        ImagePath = "";
        PinSize = 50;
        PinZoomVisibilityMinimumLimit = uint.MinValue;
        PinZoomVisibilityMaximumLimit = uint.MaxValue;
        AnchorPoint = new Point(0.5, 1);
        PinClickedCallback = null;
    }
    public CustomPin()
    {
        Address = "";
        Location = new Position();

        Name = "";
        Details = "";
        ImagePath = "";
        PinSize = 50;
        PinZoomVisibilityMinimumLimit = uint.MinValue;
        PinZoomVisibilityMaximumLimit = uint.MaxValue;
        AnchorPoint = new Point(0.5, 1);
        PinClickedCallback = null;
    }
}

CustomMap | PS:只需添加这三种方法

    #region
    public async static Task<string> GetAddressName(Position position)
    {
        string url = "https://maps.googleapis.com/maps/api/geocode/json";
        string additionnal_URL = "?latlng=" + position.Latitude + "," + position.Longitude
        + "&key=" + App.GOOGLE_MAP_API_KEY;

        JObject obj = await CustomMap.GoogleAPIHttpRequest(url, additionnal_URL);

        string address_name;
        try
        {
            address_name = (obj["results"][0]["formatted_address"]).ToString();
        }
        catch (Exception)
        {
            return ("");
        }
        return (address_name);
    }
    public async static Task<Position> GetAddressPosition(string name)
    {
        string url = "https://maps.googleapis.com/maps/api/geocode/json";
        string additionnal_URL = "?address=" + name
        + "&key=" + App.GOOGLE_MAP_API_KEY;

        JObject obj = await CustomMap.GoogleAPIHttpRequest(url, additionnal_URL);

        Position position;
        try
        {
            position = new Position(Double.Parse((obj["results"][0]["geometry"]["location"]["lat"]).ToString()),
                                    Double.Parse((obj["results"][0]["geometry"]["location"]["lng"]).ToString()));
        }
        catch (Exception)
        {
            position = new Position();
        }
        return (position);
    }

    private static async Task<JObject> GoogleAPIHttpRequest(string url, string additionnal_URL)
    {
        try
        {
            var client = new HttpClient();
            client.BaseAddress = new Uri(url);

            var content = new StringContent("{}", Encoding.UTF8, "application/json");
            HttpResponseMessage response = null;
            try
            {
                response = await client.PostAsync(additionnal_URL, content);
            }
            catch (Exception)
            {
                return (null);
            }
            string result = await response.Content.ReadAsStringAsync();
            if (result != null)
            {
                try
                {
                    return JObject.Parse(result);
                }
                catch (Exception)
                {
                    return (null);
                }
            }
            else
            {
                return (null);
            }
        }
        catch (Exception)
        {
            return (null);
        }
    }
    #endregion

MainPage.xaml.cs | PS:PCL部分,只需更改构造函数

即可
    public MainPage()
    {
        base.BindingContext = this;

        CustomPins = new List<CustomPin>()
        {
            new CustomPin("Long Beach") { Name = "Le Mans", Details = "Famous city for race driver !", ImagePath = "CustomIconImage.png", PinZoomVisibilityMinimumLimit = 0, PinZoomVisibilityMaximumLimit = 150, PinSize = 75},
           new CustomPin() { Name = "Ruaudin", Details = "Where I'm coming from.", ImagePath = "CustomIconImage.png", PinZoomVisibilityMinimumLimit = 75, PinSize = 65 },
            new CustomPin() { Name = "Chelles", Details = "Someone there.", ImagePath = "CustomIconImage.png", PinZoomVisibilityMinimumLimit = 50, PinSize = 70 },
            new CustomPin() { Name = "Lille", Details = "Le nord..", ImagePath = "CustomIconImage.png", PinZoomVisibilityMinimumLimit = 44, PinSize = 40 },
            new CustomPin() { Name = "Limoges", Details = "I have been there ! :o", ImagePath = "CustomIconImage.png", PinZoomVisibilityMinimumLimit = 65, PinSize = 20 },
            new CustomPin() { Name = "Douarnenez", Details = "A trip..", ImagePath = "CustomIconImage.png", PinZoomVisibilityMinimumLimit = 110, PinSize = 50 }
        };

        Debug.WriteLine("Initialization done.");

        PinActionClicked = PinClickedCallback;

        PinsSize = Convert.ToUInt32(100);

        MinValue = 50;
        MaxValue = 100;

        InitializeComponent();
        Debug.WriteLine("Components done.");
    }

也许它很容易,或者说我说它是唯一的方式,但我不知道如果引脚被编辑,如何在地图上更新引脚,因为最后,它仍然是同一个对象,所以列表没有不要改变......

感谢您的帮助!

编辑1

好的,我做了一些更改,但它仍然无效..我的意思是我的代码按照我的意愿工作,但调用PropertyChanged并没有改变任何东西......

我更改了List<CustomPin>现在ObservableCollection<CustomPin>之类的内容。此外,我将xaml部分更改为:

<control:CustomMap x:Name="MapTest" CustomPins="{Binding CustomPins}" CameraFocusParameter="OnPins"
                   PinSize="{Binding PinsSize, Converter={StaticResource Uint}}"
                   PinClickedCallback="{Binding PinActionClicked}"
                   VerticalOptions="Fill" HorizontalOptions="Fill"/>

我的CustomPin现在就是这样:

public class CustomPin : BindableObject, INotifyPropertyChanged
{
    /// <summary>
    /// Handler for event of updating or changing the 
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;

    public static readonly BindableProperty AddressProperty =
        BindableProperty.Create(nameof(Address), typeof(string), typeof(CustomPin), "",
            propertyChanged: OnAddressPropertyChanged);
    public string Address
    {
        get { return (string)GetValue(AddressProperty); }
        set { SetValue(AddressProperty, value); }
    }
    private static void OnAddressPropertyChanged(BindableObject bindable, object oldValue, object newValue)
    {
        (bindable as CustomPin).SetAddress(newValue as string);
        Debug.WriteLine("Address property changed");
    }
    private async void SetAddress(string address)
    {
        if (setter == SetFrom.None)
        {
            setter = SetFrom.Address;
            SetLocation(await CustomMap.GetAddressPosition(address));
            setter = SetFrom.None;
            NotifyChanges();
        }
        else if (setter == SetFrom.Location)
        {
            setter = SetFrom.Done;
            SetValue(AddressProperty, address);
        }
    }

    private enum SetFrom
    {
        Address,
        Done,
        Location,
        None,
    }
    private SetFrom setter;

    private async void SetLocation(Position location)
    {
        if (setter == SetFrom.None)
        {
            setter = SetFrom.Location;
            SetAddress(await CustomMap.GetAddressName(location));
            setter = SetFrom.None;
            NotifyChanges();
        }
        else if (setter == SetFrom.Address)
        {
            setter = SetFrom.Done;
            SetValue(LocationProperty, location);
        }
    }

    public static readonly BindableProperty LocationProperty =
      BindableProperty.Create(nameof(Location), typeof(Position), typeof(CustomPin), new Position(),
          propertyChanged: OnLocationPropertyChanged);
    public Position Location
    {
        get { return (Position)GetValue(LocationProperty); }
        set { SetValue(LocationProperty, value); }
    }
    private static async void OnLocationPropertyChanged(BindableObject bindable, object oldValue, object newValue)
    {
        (bindable as CustomPin).SetLocation((Position)newValue);
        Debug.WriteLine("Location property changed");
    }

    private void NotifyChanges()
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Address)));
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Location)));
    }

    public string Name { get; set; }
    public string Details { get; set; }
    public string ImagePath { get; set; }
    public uint PinSize { get; set; }
    public uint PinZoomVisibilityMinimumLimit { get; set; }
    public uint PinZoomVisibilityMaximumLimit { get; set; }
    public Point AnchorPoint { get; set; }
    public Action<CustomPin> PinClickedCallback { get; set; }

    public CustomPin(Position location)
    {
        setter = SetFrom.None;
        Location = location;
        Name = "";
        Details = "";
        ImagePath = "";
        PinSize = 50;
        PinZoomVisibilityMinimumLimit = uint.MinValue;
        PinZoomVisibilityMaximumLimit = uint.MaxValue;
        AnchorPoint = new Point(0.5, 1);
        PinClickedCallback = null;
    }
    public CustomPin(string address)
    {
        setter = SetFrom.None;
        Address = address;
        Name = "";
        Details = "";
        ImagePath = "";
        PinSize = 50;
        PinZoomVisibilityMinimumLimit = uint.MinValue;
        PinZoomVisibilityMaximumLimit = uint.MaxValue;
        AnchorPoint = new Point(0.5, 1);
        PinClickedCallback = null;
    }
    public CustomPin()
    {
        setter = SetFrom.None;
        Address = "";
        Location = new Position();
        Name = "";
        Details = "";
        ImagePath = "";
        PinSize = 50;
        PinZoomVisibilityMinimumLimit = uint.MinValue;
        PinZoomVisibilityMaximumLimit = uint.MaxValue;
        AnchorPoint = new Point(0.5, 1);
        PinClickedCallback = null;
    }
}

最后,PropertyChanged的电话没有做任何事情......任何想法?

谢谢!

PS:不要忘记我的github存储库中提供了该解决方案

3 个答案:

答案 0 :(得分:0)

您应该在Pin实施中使用INotifyPropertyChanged。这样,当您更新某些参数时,您会通知更改并可以更新地图。

答案 1 :(得分:0)

前一段时间面对类似的问题,为我解决的问题是改变了xaml中的绑定:

CustomPins="{Binding CustomPins}"

到此:

CustomPins="{Binding CustomPins, Mode=TwoWay}"

答案 2 :(得分:0)

我终于有了主意!在Xamarin表单中,App可以从任何地方加入,所以我做的是:

  • MainPage.xaml.cs中创建一个调用PropertyChanged事件的方法。你可以这样做:

    public void PinsCollectionChanged()
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CustomPins)));
        Debug.WriteLine("Updated !!!");
    }
    
  • 然后,从列表中的项目(对我来说,它是CustomPin对象),通过获取应用程序的当前实例来调用此方法。看一下代码来理解:

    private void NotifyChanges()
    {
        (App.Current.MainPage as MainPage).PinsCollectionChanged();
    }
    

PS:不要忘记在对象中添加using MapPinsProject.Page;

希望它有所帮助!