【发布时间】:2019-06-30 15:56:22
【问题描述】:
我在 Xamarin 表单中创建了一个 ListView 并绑定到视图模型中的 Observable 集合,通过调用 OnPropertyChanged 事件将项目动态添加到 ListView 工作正常。
但是在从服务获取状态更新后,我正在更新相应的 ListView 项目状态并调用 OnPropertyChanged 事件以及将 ListView 项目重新分配给它,但没有得到更新的 GUI,有时工作正常,有时不工作。
下面是我完成的示例代码。
<ListView Grid.Row="3" HasUnevenRows="True" ItemsSource="{Binding ServiceList}" IsPullToRefreshEnabled="True" SeparatorColor="Black">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Vertical" Spacing="4" Padding="5" BackgroundColor="LightGray">
<Label Text="{Binding OperationStatus, Converter={x:Static local:StatusMessageConverter.Default}}" FontSize="13" FontAttributes="Bold" TextColor="White" BackgroundColor="DarkCyan" />
<Label Text="{Binding Operation}" FontSize="10" Margin="10,0,0,0" />
<Label Text="{Binding OperationType}" FontSize="10" Margin="10,0,0,0" />
<Label Text="{Binding OperationStatus}" LineBreakMode="WordWrap" IsVisible="{Binding CanStatusVisible}" FontSize="10" Margin="10,0,0,0" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
public class ServiceViewModel : INotifyPropertyChanged
{
public ObservableCollection<ServiceItem> ServiceList
{
get
{
return _serviceList;
}
set
{
_serviceList = value;
OnPropertyChanged("ServiceList");
}
}
var tempList = new ObservableCollection<ServiceItem>();
tempList = ServiceList;
var targetItem = from item in tempList
where item.UniqueId == uniqueId
select item;
if (targetItem.Any())
{
var resultItem = targetItem.FirstOrDefault();
resultItem.CanStatusVisible = true;
resultItem.OperationStatus = string.Format("{0}: {1}", "Status Message", resultMessage);
}
ServiceList = null;
ServiceList = tempList;
OnPropertyChanged("ServiceList");
}
public class ServiceItem
{
public string UniqueId { get; set; }
public string Operation { get; set; }
public string OperationType { get; set; }
public string OperationStatus { get; set; }
public string StatusMessage { get; set; }
public bool CanStatusVisible { get; set; }
}
【问题讨论】:
-
您的 ServiceItem 类是否实现了 INotify PropertyChanged?
-
我已将其添加到 ViewModel
-
正如@BrunoCaceiro 所说,您的 ServiceItem 类需要实现 INPC 以便通知 UI 其属性的更改
-
是的!我正在检查.. :)
标签: c# listview xamarin xamarin.forms