MVVMLight-- Passing a parameter to a ViewModel constructor?
Suppose I have a ListBox which is bound to a collection of Foo
objects, and the selected Foo
is displayed in a contentcontrol 开发者_运维百科with the content template being a FooView
.
Is there a way that I can make it so that the FooView
passes the selected Foo
to the constructor of the FooViewModel
which is it's datacontext via the ViewModelLocator
?
MainViewModel
/*INotifyPropertChanged property*/
public FooViewModel CurrentFooVM{
get{/*INPC code*/}
private set{/*INPC code*/}
}
/*INotifyPropertChanged property*/
public Foo SelectedFoo{
get{/*INPC code*/}
set{/*INPC code*/ CurrentFooVM = new FooViewModel(_selectedFoo)}
}
public ObservableCollection<Foo> Foos {get; private set;}
MainView
<ListBox ItemsSource={Binding Foos}
SelectedItem={Binding SelectedFoo}>...
<FooView... bind to CurrentFooVM...
I heard that although the tooling in Visual Studio does not support it, the XML spec does allow you to instanciate a class with a parameter in the constructor. I've never done it, but heard that this was possible on the .Net Rocks podcast. May also be only relevant to WPF as opposed to Silverlight, as WPF has more features than Silverlight. Not much help, but may put you on the right track.
精彩评论