简单的 WPF + MVVM 绑定
我有一个名为 MyWindow
的类,它派生自 Window
。我使用 MVVM 模式,因此在代码隐藏中我有以下字段:
public MyViewModel ViewModel = new MyViewModel();
ViewModel
包含 Person
的集合,我想做的就是绑定一个 < code>ComboBox 到此集合,将 Person.Name
显示为每个 Person
的标题。
我还希望在 ViewModel
中有另一个字段,该字段将数据绑定到所选项目。
请帮我。
I have a class named MyWindow
the derives from Window
. I use the MVVM pattern so in code-behind I have the following field:
public MyViewModel ViewModel = new MyViewModel();
ViewModel
contains a collection of Person
, and all I'd like to do is to bind a ComboBox
to this collection, show Person.Name
as the header for each Person
.
I would also like to have another field in ViewModel
that will be data-bound to the selected item.
Please help me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,如果您还没有这样做,则必须将窗口的数据上下文设置为构造函数中的 viewmdodel:
然后您可以按如下方式设置 ComboBox:
其中 Persons 是人员集合,当前人员是所选人员的属性将受到约束。
Well firstly you have to set the datacontext of your window to the viewmdodel in the constructor if you have not already done so:
Then you can set the ComboBox as follows:
Where Persons is the Collection of Persons and Current Person is the Property the selected person will be bound to.
这假设您的 modelView 有一个属性 PersonCollection(它是 Person 对象的集合)、Person 对象上的属性 Name 以及类型 Person 的 modelView 上的属性 SelectedPerson。
<ComboBox ItemsSource="{Binding PersonCollection}"
DisplayMemberPath="Name"
SelectedValue="{Binding SelectedPerson}" >
</ComboBox>
This assumes that your modelView has a property PersonCollection which is a collection of Person objects, a property Name on the Person object, and a property SelectedPerson on the modelView of type Person.