如何使用 TwoWay 模式将 Listview SelectedItem 绑定到文本框?
我对 WPF 非常陌生,正在测试一些我想包含在我将要开发的应用程序中的东西。我有一个 2 行 ListView(绑定到文本框),其中包含 Scott Guthrie 和 Jon Skeet 的名字。我试图在 ListView 中选择“Scott Guthrie”并让它填充文本框。我希望能够编辑文本并关闭选项卡并更新 ListView。
编辑:我删除了代码,因为它确实没有为问题添加任何内容。
I am very new to WPF and testing some things that I would like to include in an application that I will be working on. I have a 2 row ListView (bound to a textbox) with the names Scott Guthrie and Jon Skeet in it. I am trying to select "Scott Guthrie" in the ListView and have it populate the TextBox. I want to be able to edit the text and tab off and have the ListView updated.
Edit:I removed the code since that really didn't add anything to the question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
哇,你那里的东西真的很复杂。
这可以通过非常简单的方式来完成。您需要一个模型来表示程序员,一个视图模型来保存程序员列表,以及简单的绑定来处理其余的事情。
模型:
非常简单。代表具有名字的程序员的对象。我们必须将名称封装在一个对象中,因为字符串在 .NET 中是不可变的。如果您尝试绑定字符串列表中的单个字符串,则更改不会传播。
程序员的集合保存在 ViewModel 中。在这种情况下,我将其称为ViewModel,因为我没有想象力。该视图模型包含视图绑定的所有内容。在本例中,它是程序员列表。
ViewModel 被设置为我们视图的 DataContext。 DataContext 沿着可视树向下流动,我们可以在任何点绑定它。
您可以按照您想要的任何方式设置 DataContext;为了简单起见,我在这里这样做。
在 UI 中,我只需将 ListView 绑定到 ViewModel 中的程序员列表(DataContext,除非另有说明,是绑定路径的根)。然后,我将 TextBox 绑定到 ListBox 的 SelectedItem。您从列表中选择一个程序员,然后该项目将成为 SelectedItem,然后我可以更改其名称。
很简单,一旦你掌握了它的窍门。
Wow, that's really complicated what you've got there.
This can be accomplished in a very simple way. You need a model to represent the programmer, a view model to hold a list of programmers, and simple binding to take care of the rest.
The model:
Its very simple. An object representing a programmer with a name. We must encapsulate the name within an object because strings are immutable in .NET. If you tried binding against a single string in a list of strings, changes wouldn't propagate.
The collection of programmers is kept in a ViewModel. In this case, I call it ViewModel, because I have no imagination. This view model contains everything that the view binds against. In this case, its the list of programmers.
The ViewModel is set as the DataContext of our view. The DataContext flows down the visual tree, and we can bind against it at any point.
You can set the DataContext in any way you want; I'm doing it here for simplicity's sake.
In the UI, I simply bind the ListView against the list of Programmers in the ViewModel (the DataContext, unless otherwise stated, is the root of the binding path). I then bind the TextBox against the SelectedItem of the ListBox. You select a Programmer from the list, which then becomes the SelectedItem, which I can then change the Name of.
Simple, once you get the hang of it.
这是可行的(除了您需要验证文本框,因为您可以输入任何文本......下拉列表可能是更好的选择)。
视图:
视图模型:
This works (except that you need to validate the textbox since you can enter any text.. a dropdown might be a better choice).
View:
ViewModel: