【发布时间】:2020-04-06 20:10:26
【问题描述】:
我正在 xamarin.forms 中开发一个聊天应用程序。绑定到我的聊天列表视图页面的视图模型有一个 API 调用,它将获取聊天数据并绑定到列表视图。该 API 只会调用一次,即;当我们打开页面时。我想要做的是每 10 秒调用一次 API 并在有新消息时更新列表视图。但是发生的事情不是更新列表,而是复制整个数据。我认为如果再次调用 API 是正常的,它将重新绑定整个数据。如果有任何新消息可用,如何使此更新成为列表视图?就像聊天应用程序一样。感谢任何帮助或指导。
API 数据将根据参数分配给传入和传出单元格。
我的视图模型;
public class ChatPageViewModel : INotifyPropertyChanged
{
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public INavigation Navigation { get; set; }
public string APropertyToSet { get; set; }
public ObservableCollection<NCMessage> Messages { get; set; } = new ObservableCollection<NCMessage>();
public ObservableCollection<ChatData> ChatListObj { get; set; }
public ChatPageViewModel(INavigation navigation)
{
// This is how I call the timer
Device.StartTimer(TimeSpan.FromSeconds(10), () =>
{
Device.BeginInvokeOnMainThread(async () =>
{
await loadChatList();
});
return true;
});
// <--------------- Load chat List API-------------------->
async Task loadChatList()
{
await Task.Run(async () =>
{
try
{
// API call is the dedicated class for makin API call
APICall callForNotificationList = new APICall("apicallUrl/CallChatList", null, null, "GET");
try
{
ChatListObj = callForNotificationList.APICallResult<ObservableCollection<ChatData>>();
if (ChatListObj[0].results.Count != null && ChatListObj[0].results.Count != 0)
{
if (ChatListObj[0].success)
{
foreach (var item in ChatListObj[0].results)
{
if (item.type == "user")
{
if (!string.IsNullOrEmpty(item.message))
{
var message = new NCMessage
{
Text = item.message.ToString(),
IsIncoming = "True"
};
Messages.Add(message);
}
}
}
}
else
{
//error message
}
}
else
{
//error message
}
}
catch (Exception e)
{
}
}
catch (Exception ex)
{
}
});
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
我的聊天 XAML
<ListView
ItemTemplate="{StaticResource MessageTemplateSelector}"
ItemsSource="{Binding Messages,Mode=OneWay}"
Margin="0"
BackgroundColor="Transparent"
SelectionMode="None"
FlowDirection="RightToLeft"
HasUnevenRows="True" x:Name="ChatList"
VerticalOptions="FillAndExpand"
SeparatorColor="Transparent"
>
</ListView>
我的 XAML.cs
public partial class ChatPage : ContentPage
{
ChatPageViewModel vm;
public ChatPage()
{
InitializeComponent();
this.BindingContext = vm = new ChatPageViewModel(Navigation);
}
protected async override void OnAppearing()
{
base.OnAppearing();
await Task.Delay(2000);
await vm.loadChatList();
}
}
【问题讨论】:
标签: xamarin xamarin.forms