Xamarin中TextCell绑定文本不显示问题排查及解决
Xamarin ListView TextCell绑定首次加载无文本显示问题及解决方法
问题现象
ListView绑定ViewModel中Model的Guests属性(该属性为Newtonsoft反序列化生成的ObservableCollection<string>,已添加JsonProperty特性保证setter被调用,测试数据共12条),使用TextCell并通过{Binding .}绑定文本时,首次加载单元格已渲染但无文本显示。通过热重载移除绑定中的“.”再保存,文本会正常显示;重新添加“.”后文本也能正常更新,修改TextColor属性也存在类似首次不生效的情况,疑似首次加载时绑定逻辑异常。
相关代码
初始视图代码
<ListView ItemsSource="{Binding Guests}" Margin="0" HeightRequest="300" VerticalOptions="FillAndExpand" RowHeight="28" SelectionMode="None"> <ListView.ItemTemplate> <DataTemplate> <TextCell Text="{Binding .}" TextColor="{StaticResource BT-DarkGray}"/> </DataTemplate> </ListView.ItemTemplate> </ListView>
Model代码
private ObservableCollection<string> _guest; [JsonProperty("guests")] public ObservableCollection<string> Guests { get => _guest; set => SetProperty(ref _guest, value); } private ObservableCollection<LocalShowFlight> _flights; [JsonProperty("flights")] public ObservableCollection<LocalShowFlight> Flights { get => _flights; set => SetProperty(ref _flights, value); } private ObservableCollection<LocalShowTiming> _timings; [JsonProperty("timings")] public ObservableCollection<LocalShowTiming> Timings { get => _timings; set => SetProperty(ref _timings, value); } public void RaisCollectionChanged() { OnPropertyChanged(nameof(Guests)); OnPropertyChanged(nameof(Flights)); OnPropertyChanged(nameof(TimingOther)); }
ViewModel代码
public ShowBandAppModelV2 Model { get { return _model; } set { SetProperty(ref _model, value); Model?.RaisCollectionChanged(); } }
解决方法
将TextCell替换为包含Label的ViewCell,并为DataTemplate指定x:DataType="x:String",修改后的视图代码如下:
<ListView.ItemTemplate> <DataTemplate x:DataType="x:String"> <ViewCell> <Label Text="{Binding .}" TextColor="{StaticResource BT-DarkGray}" VerticalTextAlignment="Start" LineBreakMode="TailTruncation"/> </ViewCell> </DataTemplate> </ListView.ItemTemplate>
内容的提问来源于stack exchange,提问作者Bart Peirens
相关产品推荐
相关产品推荐

