I have a question, is it correct to initialize a property full
in ViewModel
the following way?
public class MainViewModel : ViewModelBase
{
private ObservableCollection<Driver> _drivers = new ObservableCollection<Driver>();
public ObservableCollection<Driver> Drivers
{
get { return _drivers; }
set { _drivers = value;
RaisePropertyChanged();
}
}
}
Is it correct? Is it a bad practice? Or should it be done in another way? My question arises because I was trying to fill that collection with a method that initialized the field but the changes were not reflected in the XAML
one that is bound to the property Drivers
, only instantiating the field _drivers
in this way made it work. Thanks.
I don't see it wrong, but I would recommend initializing in the constructor of the
ViewModel
Be careful , it seems that you are implementing INotifyPropertyChanged, if you bind to a property before instantiating it, and you instantiate it like this:
You are not going to call the Setter of the property and therefore the XAML (GUI) is not going to react to the change.
That is, you have:
And you are creating an instance of the private _drivers field, without going through the Drivers observable property, the XAML (GUI) will not notice the change
Create the instance using the observable property to "tell" the GUI that there is a new instance:
Regardless of this and answering your original question, I recommend instantiating your properties and variables in the constructor, or even in a separate method eg "Initialize()" and call this method from the constructor, so you have more control over where you are creating your instances , but this depends on the preferences of each person
You can even have your properties in a static class and have them globally accessible to the entire application (similar to the "singleton" pattern)