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

5ssjco0h  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(44)

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

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");
                }
            }

mrphzbgm

mrphzbgm1#

社区已经指出了这个问题。我分享了一个使用数据绑定的想法。由于BookVehicleInfo也在ViewModel中设置,因此您不需要再次为label设置BindingContext,因为它将从其父级继承。
如果你想绑定BookVehicleInfo类中的属性,可以这样做,

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

字符串
然后文本可以绑定到VehicleName属性(无需在xaml中设置BindingContext)。
我认为应该有一些方法来更新ViewModel中的值。例如使用Xamarin Community Toolkit EventToCommandBehavior

相关问题