0

I hope you can help me. I have a view created in code that is bound to a viewModel and inside the view there is a ListView.

The problem is that my code that adds the controls, including the ListView, is in the view's constructor and has as a parameter the viewModel that I assign to the BindingContext of the view.

public SurveyQuestionsView(SurveyQuestionsViewModel vm)
{
    _vm = vm;
    BindingContext = _vm;

    var listView = new ListView();
    listView.ItemsSource = _vm.Questions;


    Content = listView;

}

At the time the constructor is called on the viewModel my property that serves as the data source for the listView is still null. And it is through another procedure that this property of the viewModel is filled, but I can't find a way for the View to detect that change and because of that, reload the ListView.

public partial class SurveyQuestionsViewModel : ObservableObject
{
    private readonly ISurveyApplication _surveyApplication;

    public SurveyQuestionsViewModel(ISurveyApplication surveyApplication)
    {
        _surveyApplication = surveyApplication;
        
    }
        
    [ObservableProperty]
    private ObservableCollection<SurveyQuestionModel> questions;
    
    async Task LoadData()
    {
        var data = await _surveyApplication.GetSurveyQuestionsBySurveyId(currentSurvey.SurveyId);
       Questions = new ObservableCollection<SurveyQuestionModel>(data);
    }
}

Thank you very much for your help!!

vordonez
  • 5
  • 1
  • The view knows about the viewmodel, and needs to set up something to happen when `questions` is set. A standard technique in c# is to define either an `Action` or an `event` in viewmodel, and have view set that Action (or attach to that event). In `LoadData`, after set `Questions`, call that Action (or invoke the event handler). Research `c# Action` or research `c# event handling`. – ToolmakerSteve Jun 18 '23 at 20:06
  • I would make Questions a normal public property and in the LoadData() just Questions.Clear() and foreach (var each in data) Qustions.Add(each) Why didn't they give ObservableColelctiona an AddRange()? ugh! – kenny Jun 18 '23 at 20:13
  • https://stackoverflow.com/a/8607159/3225 – kenny Jun 18 '23 at 20:29

1 Answers1

0

You're not using data binding at all - you're just directly assigning ItemsSource

to setup data binding in code, use SetBinding

listView.SetBinding(ListView.ItemsSourceProperty, nameof(Questions));

since Questions is Observable you should not need to do anything special when you assign or re-assign the property's value

Jason
  • 86,222
  • 15
  • 131
  • 146