Xamarin 表单数据绑定问题,视图未更新

问题描述 投票:0回答:1

我没有对整个页面使用绑定上下文页面或 x:DataType。我对每个组件使用单独的 x:DataType。如下所示: 主要问题是第一个组件的行为符合预期,第二个和第三个组件没有在视图中显示或更新。如果我在初始加载时设置虚拟机中的每个值,它将显示 。但它永远不会更新。

1.component is a map (it works and updates )
     <mainlocal:CustomMap.ItemTemplate>
                        <DataTemplate x:DataType="localone:PinData" >
                            <mainlocal:CustomPin PinId="{Binding PinId}"
                                              
                             Label="{Binding PinLabel}"
                             Position="{Binding PinPostion}"/>
            </DataTemplate>



<Label x:DataType="localsecond:BookVehicleInfo"
                                Grid.Row="0"  Text="{Binding VehicleName}"
                               FontSize="Large"
                               TextColor="white"
                               HorizontalOptions="Center"
                               VerticalOptions="Center">
                            <Label.BindingContext>
                                <localsecond:BookVehicleInfo />
                            </Label.BindingContext> </Label>
           

和:

public ObservableCollection<PinData> PinsCollection { get; set; } = new ObservableCollection<PinData>(); (works)
     public BookVehicleInfo person { get; } = new BookVehicleInfo(); (nope)

.

更新两个组件的事件如下

private async move()
{
//this runs a service that updates both 
person.VehicleName = "service.update ";

}

最后,

 public class BookVehicleInfo : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            public string vehiclename { get; set; }
    }
     public void OnPropertyChanged(string name)
            {
                if (this.PropertyChanged != null)
                    this.PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
     public string VehicleName
            {
                get { return vehiclename; }
                set
                {
                    vehiclename = value;
                    OnPropertyChanged("VehicleName");
                }
            }
       
ios xamarin data-binding
1个回答
0
投票

社区已指出问题。我分享了一个使用数据绑定的想法。由于 BookVehicleInfo 也在 ViewModel 中设置,因此您无需再次设置标签的 BindingContext,因为它将继承自其父级。

如果您想绑定到 BookVehicleInfo 类中的属性。你可以用这个方法,

<Label 
        Text="{Binding person.VehicleName}"
        FontSize="Large"
        HorizontalOptions="Center"
        VerticalOptions="Center">
</Label>

然后文本可以绑定到VehicleName属性(不需要在xaml中设置BindingContext)。

而且我认为应该有某种方法来更新 ViewModel 中的值。例如使用Xamarin社区工具包EventToCommandBehavior

© www.soinside.com 2019 - 2024. All rights reserved.