Wpf treeview selectedItem databinding

2019-08-20 05:23发布

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?

2条回答
不美不萌又怎样
2楼-- · 2019-08-20 06:06

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.

查看更多
虎瘦雄心在
3楼-- · 2019-08-20 06:18

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.

查看更多
登录 后发表回答