使用Xamarin表单的自定义Pin类中的数据绑定属性出现问题

j2cgzkjk  于 2023-02-27  发布在  其他
关注(0)|答案(1)|浏览(109)

我在使用Xamarin表单为自定义Pin类中的一些自定义属性设置数据绑定时遇到了麻烦。
下面是我要处理的两个自定义类。

public class CustomPin : Pin
{
    public static readonly BindableProperty NameProperty = BindableProperty.Create("Name", typeof(string), typeof(Pin), default(string));

    public string Name
    {
        get { return (string)GetValue(NameProperty); }
        set { SetValue(NameProperty, value); }
    }

    public string Icon { get; set; }
}

public class UserData
{
    public string Callsign { get; set; }
    public string ID { get; set; }
    public string Team { get; set; }
    public CustomPin Pin { get; set; }
    public Position Position { get; set; }
}

下面是保存我的Bindings的值的元素。

public static UserData myUserData = new UserData
{
    Callsign = "User",
    Pin = new CustomPin
    {
        BindingContext = myUserData,
        Position = new Position(),
        Name = "",
        Label = ""
    },
    Position = new Position(),
};

下面是如何设置绑定

myUserData.Pin.SetBinding(CustomPin.PositionProperty, "Position");
myUserData.Pin.SetBinding(CustomPin.LabelProperty, "Callsign");
myUserData.Pin.SetBinding(CustomPin.NameProperty, "Callsign");

这是我用来调试

Debug.WriteLine
(
    myUserData.Pin.Name + " should be " + myUserData.Callsign + "\n" +
    myUserData.Pin.Label + " should be " + myUserData.Callsign + "\n" +
    myUserData.Pin.Position.Latitude + " should be " + myUserData.Position.Latitude + "\n" +
    myUserData.Pin.Position.Longitude + " should be " + myUserData.Position.Longitude + "\n"
);

下面是输出,正如您所看到的,它没有应用绑定--但是我确实在其他对象(如Xamarin.Forms.Label)中使用了这个绑定,它们工作得很好。

should be User
 should be User
0 should be 37.63150086
0 should be -122.43626643

提前感谢您的帮助。

b1payxdu

b1payxdu1#

就像Jason说的Pin is a UI object .你不应该把它做成一个数据类,你可以在.xaml文件中使用它,也可以像这样在c#文件中使用pin。

using Xamarin.Forms.Maps;
// ...
Map map = new Map
{
  // ...
};
Pin pin = new Pin
{
  Label = "Santa Cruz",
  Address = "The city with a boardwalk",
  Type = PinType.Place,
  Position = new Position(36.9628066, -122.0194722)
};
map.Pins.Add(pin);

相关问题