I am working on an WPF database application using the MVVM-Light Framework. I am using SimpleIOC to inject my Data Services, and my ViewModels are connected to the view from the XAML file. However, when opening new View Models I usually also need to pass another object to the View Model (lets say I am passing a integer of a CarId so I can grab the actual Car from a database).
Right now I am passing this by using a messenger on the View, after InitializeComponent(). This is then caught by the View Model. This currently does work, however it has some set backs.
First, the Message does not get sent until after the Constructor of the View Model is called. Lets say I had a ThisCar object Property in the ViewModel, and I had secondary properties like a string called Brand, that returns ThisCar.Brand.
public const string ThisPersonPropertyName = "ThisCar";
private Model.Car _thisCar;
public Model.Car ThisCar
{
get
{
return _thisCar;
}
set
{
if (_thisCar== value)
{
return;
}
RaisePropertyChanging(ThisCarPropertyName);
_thisCar= value;
RaisePropertyChanged(ThisCarPropertyName);
}
}
public const string BrandPropertyName = "Brand";
public string Brand
{
get
{
return ThisCar.Brand;
}
set
{
if (ThisCar.Brand == value)
{
return;
}
RaisePropertyChanging(BrandPropertyName);
ThisCar.Brand = value;
RaisePropertyChanged(BrandPropertyName);
}
}
Now when the constructor gets called, I have to initialize ThisCar in the View Model Constructor Like so, otherwise I get a null error on ThisCar.Brand when the ViewModel gets created.
ThisCar = new CarObject();
Then, after it is initialized to an empty object, the Message will get called, and I will pull the real Car from the Database based on the Car ID.
ThisCar = webService.GetCar(carId);
However, when I do this, the Brand Property does not get updated, because nothing is calling the OnPropertyChanged for the Brand.
I have two work arounds, but they feel more like hacks to me. First on is manually calling the OnPropertyChanged for any properties that need to be updated. Second is I remove all the small properties, and bind everything directly to the ThisCar property (which means I have to implement INotifyPropertyChanged in my model).
Please let me know if I am just being picky, or if there is a better way to do this. The way I am doing it works, but just doesn't sit right with me. Thank you.