MVVMLight— Passing a parameter to a ViewModel constructor?

偶尔善良 提交于 2019-12-07 08:20:14

问题


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?


回答1:


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...



回答2:


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.



来源:https://stackoverflow.com/questions/4505919/mvvmlight-passing-a-parameter-to-a-viewmodel-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!