【问题标题】:Binding doesn't work - No property, bindable property, or event found error绑定不起作用 - 没有属性、可绑定属性或找到事件错误
【发布时间】:2019-03-20 18:15:10
【问题描述】:

我遇到了绑定问题,但我首先搜索了几个关于此的问题,但没有运气,下面是我得到的错误:

错误:位置 18:36。未找到任何属性、可绑定属性或事件 对于 'Lat',或者值和属性之间的类型不匹配

下面是我的 xaml 文件:

<controls:MapView x:Name="map" VerticalOptions="FillAndExpand">
            <controls:MapView.Center>
                <controls:Position Lat="{Binding latitude}" Long="{Binding longitude}" />
            </controls:MapView.Center>
        </controls:MapView>

那么c#代码如下:

public partial class DisplayMap : ContentPage
    {

        private double latitude { get; } 
        private double longitude { get; } 

        public DisplayMap()
        {

            InitializeComponent();

            this.latitude = 0.3476;
            this.longitude = 32.5825;

            BindingContext = this;

        }

我错过了什么?

【问题讨论】:

  • 代码示例中的绑定使用 MapView 的 BindingContext。但是,您正在为 DisplayMap 设置 BindingContext。尝试设置 MapView 控件的 BindingContext...
  • 您使用的是哪个地图控件?你确定 Lat 和 Long 是可绑定的属性吗?
  • 我正在使用一个名为 github.com/NAXAM/mapbox-xamarin-forms@Jason 的库。让我检查他们的库是否具有可绑定属性。

标签: c# xamarin.forms


【解决方案1】:

问题似乎是Position 类中缺少可公开访问的可绑定属性(注意错误提到LatPosition 的成员)。 Position 应该是这样的:

public class Position : BindableObject
{
    public static readonly BindableProperty LatProperty = BindableProperty.Create(nameof(Lat), typeof(double), typeof(Position), 0);
    public double Lat
    {
        get { return (double)this.GetValue(LatProperty); }
        set { this.SetValue(LatProperty, value); }
    } 

    public static readonly BindableProperty LongProperty = BindableProperty.Create(nameof(Long), typeof(double), typeof(Position), 0);
    public double Long
    {
        get { return (double)this.GetValue(LongProperty); }
        set { this.SetValue(LongProperty, value); }
    }

    // ...

我建议你看看official documentation for Bindable Properties。本质上,您收到的错误消息是因为它在尝试使用访问器 Lat 进行绑定时正在寻找 LatProperty

【讨论】:

  • 所以这意味着我无法绑定,除非我将 mapView 库编辑到此代码。
  • @LutaayaHuzaifahIdris 如果在库中他们没有将 LatLong 实现为可绑定属性,那么您可以尝试在库本身中编辑 Position 类,或者在您的项目中,您可以创建一个继承自Position 的新类并在该新类中实现可绑定属性(如果您可以覆盖LatLong,那么这可能是最简单的)。
  • 其实我已经开始编辑它了,但是this.GetValuethis.SetValue 在当前上下文中不存在。我还阅读了您提供的文档链接。
  • 确保你的类继承自BindableObject,这就是定义这些方法的地方。
  • 如果你想避免绑定,这样的事情应该可以工作...... XAML:&lt;controls:MapView x:Name="map" VerticalOptions="FillAndExpand" /&gt;。后面的代码(在DisplayMap 构造函数中):this.map.Center = new Position { Lat = this.latitude, Long = this.longitude };
【解决方案2】:

您无法使用 Lat 和 Long 属性的原因是,如果您检查 Position 类,其中没有为它们定义可绑定属性,这意味着您无法在 XAML 中访问它们,

一种可能的解决方案是下载示例项目并获取代码并对其进行相应更改以使其具有可绑定属性。

为此,您可以查看@Aaron 的答案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多