Wpf 树视图 selectedItem 数据绑定
我有一个视图,其中有一个对象绑定到树视图。该对象有许多集合(不同类型),因此我使用带有 CompositeCollection 的分层模板来在树视图中显示它们。
然后我得到了一个绑定到树视图的 selectedItem 的文本框。在这里,我将 selectedItem 序列化为 XML 并将其显示在文本框中进行编辑。
到目前为止一切都很好。但是,我遇到的大问题是我无法将 2 路数据绑定与树视图的 SelectedItem 属性一起使用,因为它是只读的。
如何使文本框编辑与绑定到树视图的对象保持同步?
I have a view where I've got an object bound to a treeview. The object has a number of collections (of different types) so I'm using hiearchical templates with a CompositeCollection to display them in the treeview.
I've then got a textbox that is bound to the treeview's selectedItem. Here I'm serialising the selectedItem to XML and displaying it in the textbox for editing.
All good so far. However, the big problem I have is that I can't use 2-way databinding with the SelectedItem property of the treeview as it is read only.
How can I cleanly keep the textbox edits in sync with my object that is bound to the treeview?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您不需要对 SelectedItem 本身进行双向数据绑定,您应该在绑定对象的类中公开一个属性,该属性返回序列化字符串,并在
set
上适当地修改该对象。这应该比处理整个对象更容易。I do not think you need to do two-way databinding on the SelectedItem itself, you should expose a property in the class of your bound object which returns the serialized string and upon
set
modifies the object appropriately. This should be easier than dealing with the object as a whole.您的 XML 流必须表示为 SelectedItem 节点上的属性,并且您的 TextBox 必须以某种方式绑定到该属性。 SelectedItem 是只读的,但它引用的对象不是。如果您对该属性进行双向绑定,您应该能够正确影响您的编辑。这将在您使用的 DataTemplates 和 HiearchicalDataTemplates 中完成,因为它们绑定到您使用 TreeView 表示的节点的基础数据表示形式。
Your XML stream must be represented as a property on your SelectedItem node, and your TextBox must be bound to that, somehow. The SelectedItem is read-only, but the object it refers to is not. If you two-way bind on that property, you should be able to affect your edits correctly. This would be done in the DataTemplates and HiearchicalDataTemplates you are using, since they are bound to the underlying data representation of the nodes you are representing with the TreeView.