ViewModel communication question
Imagine I have a UserControl that shows a parking lot (my favorite analogy) with cars of different colors. You can select a car, and in a separate UserControl (in a separate project) statistics of the selected car are displayed.
Now a user wants a button on the car statistics UC, 'Next car of same color'. When sele开发者_Go百科cted it should show the statistics of the next car (top to bottom, left to right) on the parking lot with that same color.
So if that makes sense, on to the question.
I am currently using MVVM Lite to send a message containing the selected car from the parking lot UC to the car statistic UC. All is good. Now though, with this new feature request, what should I do? The statistic UC needs to request the next car from the parking lot UC.
Would this be a good place to use dependency injection? Or is there another better approach?
If I am getting you right, what you want is a Command with proper CommandParameters.
public class Car
{
public Car(ParkingLot lot)
{
_parkingLot = lot;
}
public string Color { get; set; }
public ParkingLot ParkingLot
{
get
{
return _parkingLot;
}
}
private ParkingLot _parkingLot;
}
public class ParkingLot : ObservableCollection<Car>
{
public Car SelectedCar { get; set; }
public ICommand ShowNextCarCommand {
get
{
if (_showNextCar == null)
{
_showNextCar = new DelegateCommand(OnShowNextCar);
}
return _showNextCar;
}
}
private void OnShowNextCar()
{
string currentColor = SelectedCar.Color;
//Write proper logic to get the next Car. Here you got the currently selected car with you and the color
SelectedCar = this.NEXT(s => s.Color == currentColor); //Write the NEXT() logic
}
ICommand _showNextCar;
}
Now it is a matter of setting Button.Command="{Binding ParkingLot.ShowNextCarCommand}" now you got your control over to the ParkingLot viewmodel class and find the Next same colored car and set it again to SelectedCar property. I assume you will have RaisepropertyChanged in all these properties. I use simple DelegateCommand of Prism
I would use a Controller as mediator between the two ViewModels (ParkingLotViewModel and StatisticsViewModel). In your case the Controller is responsible to synchronize the selected car and it is responsible to pass the ‘Select next car of same color’ command to the ParkingLotViewModel.
The sample applications of the WPF Application Framework (WAF) show how this can work.
.
jbe
精彩评论