Anand
Anand

Reputation: 1959

Xamarin forms value does not bind to UI from viewmodel

I am trying to create a chat application in xamarin.forms. For rest of all my screens I am not using MVVM pattern. But I am trying to implement MVVM pattern in chat portion. So basically my chat view is a listview with incoming and outgoing message template.I will try to call a API in my viewmodel and trying to bind the result into view.I can get the value from API but can't make it bind to view.

In order to get the API result, I need to pass a unique id fetched from previous page when user click on chat option.So I have two doubts.

  1. As I said I am not using MVVM pattern, I pass the unique ID from previous page to chat page view model through messaging center. Is this the correct way to pass value from one code behind to another page viewmodel?
  2. The message does not bind to the UI.

My viewmodel

public class ChatPageViewModel : INotifyPropertyChanged
{      

    public INavigation Navigation { get; set; }
    public ObservableCollection<NCMessage> Messages { get; set; } = new ObservableCollection<NCMessage>();
    public string TextToSend { get; set; }
    ObservableCollection<ChatData> ChatListObj;

    public ICommand OnSendCommand { get; set; }
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public ChatPageViewModel(INavigation navigation)
    {
        MessagingCenter.Subscribe<MyMessage>(this, "ChatClicked", async (value) =>
        {
            string receivedData = value.Myvalue;
            await loadChatList(value.Myvalue);
        });

        OnSendCommand = new Command(() =>
        {
            if (!string.IsNullOrEmpty(TextToSend))
            {
                var urlStr = TextToSend;         
                var message = new NCMessage
                {
                    Text = urlStr.ToString(),
                    IsIncoming = false,
                    MessageDateTime = DateTime.Now
                };
                Messages.Add(message);
                TextToSend = string.Empty;
            }

        });

    }

    // My chatlist API call
    public async Task loadChatList(string Type)
    {
        await Task.Run(() =>
        {
            try
            {                                  
                NCAPICall callForNotificationList = new NCAPICall("MyHeader", null, null);
                try
                {
                    ChatListObj = callForNotificationList.APICallResult<ObservableCollection<ChatData>>();
                    if (ChatListObj[0].success)
                    {       
                        // This value not updating  in UI
                        Messages.Insert(0, new NCMessage() { Text = "Sample msg", IsIncoming = true });
                    }

                }
                catch (Exception e)
                {                       
                }

            }
            catch (Exception)
            {

            }
        });
    }        
}

If I provide Messages.Insert(0, new NCMessage() { Text = "Sample msg", IsIncoming = true });directly into viewmodel, it will show.

My ChatPage.xaml.cs

 public partial class ChatPage : ContentPage
    {
       ChatPageViewModel vm;
        public ChatPage(NCDatamodel.Result notificationListData)
        {
            InitializeComponent();
            this.BindingContext = vm = new ChatPageViewModel(Navigation)           
        }    
    }

Any help is appreciated.

Upvotes: 0

Views: 345

Answers (1)

FlaGon
FlaGon

Reputation: 114

A quick and dirty approach would be to set a public property in your ViewModel from the constructor of ChatPage. Then you can override OnAppearing in ChatPage and call loadChatList.

Upvotes: 0

Related Questions