使用代码更新 TreeViewItem 的绑定? (XAML/WPF)
我有一个 TreeView
,其 ItemsSource
设置为我拥有的模型。 3 层深是一个状态可以更改的对象,我不想为每个阶段编写 View 和 ViewModel(非常冗长的业务),而是只想使用代码更新它。
所以基本上我有一个事件,一旦我的模型更新就会触发,我捕获它然后找到与该数据位关联的 TreeViewItem
。我现在的问题是我不知道如何更新它的绑定以反映新值!
有人可以帮忙吗?
我知道这不是最佳实践,但我真的不想浪费时间编写大量代码来更新一件事。
谢谢 克里斯
I have a TreeView
whose ItemsSource
is set to a Model I have. 3 levels deep is an object whose state can change and, rather than write a View and ViewModel for each stage (very lengthy business) I wanted to just update this using code.
So basically I have an event that is fired once my model updates, I catch it then find the TreeViewItem
associated with this bit of data. My issue now is I have NO idea on how to update the binding on it to reflect the new value!
Can anyone help?
I know this isn't best practice but I really don't want to have to waste time writing a massive amount of code to just update one thing.
Thanks
Chris
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您确定在相关类上实现 INotifyPropertyChanged 不会更容易吗?
Are you sure it wouldn't be easier to implement INotifyPropertyChanged on the relevant class?
这个示例有效,尽管它只有两层(而不是三层)深。它显示了一个简单的 2 级分层树视图,其中包含父项 A、B 和 C,以及编号的子项(A.1、B.1 等)。单击“重命名 B.1”按钮时,会将 B.1 重命名为“Sylvia”。
这是一个 hack,但每次 ItemsSource 属性更改时它都会重新评估 DataTemplate。
理想情况下,您可以在该 TreeViewItem 绑定到的模型对象类上实现 INotifyPropertyChanged,并让它在该值更改时触发 PropertyChanged 事件。事实上,您应该小心不要发生内存泄漏,因为它不会: 查找 WPF 应用程序中的内存泄漏。
This example works, though it's only two (not 3) levels deep. It shows a simple 2-level hierarchical treeview with parent items A, B, and C, with numbered children (A.1, B.1, etc). When the Rename B.1 button is clicked, it renames B.1 to "Sylvia".
This is a hack, but it re-evaluates the DataTemplate every time it's ItemsSource property changes.
Ideally, you would implement INotifyPropertyChanged on your model object class that this TreeViewItem is bound to, and have it fire the PropertyChanged event when that value changes. In fact, you should be careful that you aren't incurring a memory leak because it doesn't: Finding memory-leaks in WPF Applications.
听起来您可能需要查看
UpdateSource
和UpdateTarget
方法。我
尽管 当您实际将 TreeView 的
ItemSource
绑定到分层数据结构时,我不完全确定这是否有效,但这是我要开始调查的地方。Sounds like you might need to take a look at the
UpdateSource
andUpdateTarget
methods.MSDN reference for UpdateSource
Although I'm not totally sure this will work when you've actually bound the TreeView's
ItemSource
to a hierarchical data structure, but it's where I would start investigating.