简体   繁体   中英

Binding Issue constructor viewmodel

I relatively new to mvvm, however I have a question about binding from a viewmodel. I have a viewmodel where in its constructor I want to populate a observablecollection. My constructor looks like this:

public StudySelectionViewModel() : base() {
        _studyRepository = StudyRepository.Instance;

        InitializeViewModelData();
    }

The InitializeViewModelData() looks like this:

        private void InitializeViewModelData() {
        _studyRepository.RetrieveModalityTypes();
        RaisePropertyChanged("ModalityTypes");
    }

My property ModalityTypes looks like this:

public ObservableCollection<ModalityType> ModalityTypes {
        get {
            return _studyRepository.ModalityTypes;
        }
    }

Probably needless to say that my repository makes a call to a database and retrieves the data. When debugging it looks like that the RaisePropertyChanged is executed earlier than my _studyRepository.RetrieveModalityTypes method is executed and hence it binds to an empty property.

Am I missing something here? Is my design bad? Any ideas?

Thanks in advance,

The binding will inspect the property when the form initialises. It will also inspect the property when the PropertyChanged notification is raised - so you may get two calls to the getter of the property

I'm assuming that your call to get data is a web service call or something? Silverlight is async, so you need to consider that web service calls may return well after your form is initialised

There are two things to consider here.

  1. You have an ObservableCollection - it's observable, so if you initialise the collection when you initialise the view model, the add to the collection rather than replacing it with a new collection when your data service returns the view will update fine.
  2. If you really must replace the collection with a new collection in the data service data ready callback, then ensure you write the collection setter thus:

     public ObservableCollection<ModalityType> ModalityTypes { get { return _studyRepository.ModalityTypes; } set { this.__studyRepository.ModalityTypes = value; RaisePropertyChanged("ModalityTypes"); { 

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM