首页 > 解决方案 > WPF 根据选择突出显示树视图中的多个节点/叶子

问题描述

我有一个有界的、分层的TreeView. 根据底层数据的性质,同一个对象可能会在树中出现多次:

A
--A1
  ---A11
--A2
B
--B1
--A1      <<< A1 is a node under both A and B
  ---A11  <<< A11 also shows up twice since it is a child of A1

请注意,虽然我在示例中显示了 3 个级别,但实际数据可以有无限数量的级别。并且同一个对象可能会出现在多个级别。我TreeView的 withHierarchicalDataTemplate很好地展示了这一点。

由于 A1 可能出现在多个位置,我想向用户强调这一点,以便他们知道编辑 A1 不仅会影响 A 分支,还会影响 B 分支。

请注意,目标只是突出显示另一个 A1,而不是更改选择。

到目前为止,我得出的唯一解决方案是IsHighlighted在对象的基础类中拥有一个属性。IsHighlighted选择A1时,我会通过处理程序更改值SelctedItemChangedIsHighlighted反过来又通过转换器绑定到TreeViewItemBackground属性,并且 GUI 更新由属性更改通知触发。

这种方法的问题是我现在在我的模型中有一个纯 UI 驱动的属性。虽然我没有严格遵守 MVVM,但我想至少让模型更加孤立。

建议的实施方式是什么?

标签: wpftreeview

解决方案


我会坚持使用具有两个属性的模型:

  • 姓名
  • 突出显示

原因如下:

The logic you are talking about is, in essence, view logic, but it is not deciding how the view is displaying data; instead, it is only representing what the view is displaying. Therefore, it should reside in the view model. View models are agnostic - meaning that they don't have view objects in them (e.g. Listview, Buttons, etc..), but they are an object representation of the view (a.k.a the model of the view).


推荐阅读