MVVMLight——将参数传递给 ViewModel 构造函数?

发布于 2024-10-08 20:45:14 字数 250 浏览 0 评论 0原文

假设我有一个绑定到 Foo 对象集合的 ListBox,并且选定的 Foo 显示在内容控件中,内容模板是 FooView.

有没有办法让 FooView 将选定的 Foo 传递给 FooViewModel 的构造函数,这是它的数据上下文ViewModelLocator

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

深府石板幽径 2024-10-15 20:45:14

MainView模型

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

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...
无悔心 2024-10-15 20:45:14

我听说虽然 Visual Studio 中的工具不支持它,但 XML 规范确实允许您在构造函数中使用参数实例化一个类。我从未这样做过,但听说 .Net Rocks 播客上可以做到这一点。也可能仅与 WPF 相关,而不与 Silverlight 相关,因为 WPF 比 Silverlight 具有更多功能。没有多大帮助,但可能会让你走上正轨。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文