Where and how should selected items be managed in a MVVM architecture?
I have a view that allows the user to select some data : some dates for example, and executes a command that needs these data.
So in my command I should have a reference to the selected date, but what is the best practice to make this date go to the ViewModel side where the command lives :
- to add a SelectedDate dependency property in the ViewModel and bind my view on it, and reference 开发者_如何学Pythonit in my command via "@this.SelectedDate" (with @this a reference to the current ViewModel),
- to let the view transmit it through the "parameter" of the "Execute" method of the command, and reference the date with "DateTime selectedDate = (DateTime)parameter;",
- any other solution...
Thanks by advance.
I'd make SelectedDate
a dependency property of the view model, absolutely.
I'd also make the command get the SelectedDate
from the view model. There's no reason for the view to know anything about that.
To the first part, Yes I think the SelectedDate should be an (INotify) property of your ViewModel.
I don't have a strong opinion on where your Command should obtain this information, I think the property is OK.
The BookLibrary sample application of the WPF Application Framework (WAF) shows a way to handle the selected item with MVVM: The ViewModel has a 'SelectedBook' property which is bound to the View.
精彩评论