What is the correct way to initialize a property in MVVM

2

I have a question, is it correct to initialize a property full in ViewModel as follows?

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 since I was trying to fill that collection with a method that initialized the field but the changes were not reflected in the XAML that is linked to the property Drivers , only instantiating the field _drivers in this way I got it to work. Thanks.

    
asked by Edwin V 03.02.2016 в 21:06
source

2 answers

3

I do not see it incorrect, but I would recommend initializing in the constructor of ViewModel

public class MainViewModel : ViewModelBase
{
    public MainViewModel()
    {
        _drivers = new ObservableCollection<Driver>();
    }

    private ObservableCollection<Driver> _drivers = null;
    public ObservableCollection<Driver> Drivers
    {
        get { return _drivers; }
        set 
        { 
            _drivers = value;
            RaisePropertyChanged();
        }
    }

}
    
answered by 03.02.2016 / 21:14
source
1

Care , apparently you are implementing INotifyPropertyChanged, if you binde to a property before instantiating it, and instantiate it like this:

_drivers = new ObservableCollection<Driver>();

You are not going to call the Setter on the property and therefore, the XAML (GUI) will not react to the change.

That is, you have:

<DataGrid ItemsSource={Binding Drivers}> ... </DataGrid>

And you are creating an instance of the private field _drivers, without going through the observable Drivers property, the XAML (GUI) is not going to realize the change

Create the instance using the observable property to "warn" the GUI that there is a new instance:

Drivers = new ObservableCollection<Driver>();

Regardless of this and answering your original question, I recommend you to instantiate your properties and variables in the constructor, or even in a separate method such as "Initialize ()" and send this method from the constructor, so you have more control over where you are creating your intancias , but this depends on the preferences of each one

You can even have your properties in a static class and have them globally accessible to the whole application (similar to the "singleton" pattern)

    
answered by 03.02.2016 в 22:30