Xamarin c# <>自动更新自己,如何从他们更新列表

本文关键字:更新 他们 列表 自己 Xamarin | 更新日期: 2023-09-27 18:15:59

我正在为我的Github存储库开发xamarin解决方案。对于Pins项目,我面临着一个问题。如果你创建了一个引脚(也就是CustomPin()),然后你想编辑位置。然后地址名称会改变,同样的位置,如果你改变地址,位置将根据地址名称创建。所以从这里开始,很容易。

然而,当Pin地址/位置发生变化时,我希望我的地图更新自己。但是因为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 . example .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存储库

Xamarin c# <>自动更新自己,如何从他们更新列表

您应该在Pin实现中使用INotifyPropertyChanged。这样,当您更新一些参数时,您可以通知更改并可以更新映射。

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

CustomPins="{Binding CustomPins}"

:

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

我终于有主意了!在Xamarin Forms中,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;