2

SO上有很多这种类型的问题,但都回答了,所以我决定创建一个快速的新问题。标题是不言自明的,所以这就是问题所在。树视图:

<TreeView>
    <TreeView.Resources>
        <Style TargetType="TreeViewItem">
            <Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}" />
            <Setter Property="IsExpanded" Value="{Binding Path=IsExpanded, Mode=TwoWay}" />
            <Setter Property="FontWeight" Value="Normal" />
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="FontWeight" Value="Bold" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </TreeView.Resources>
</TreeView>

分层数据模板:

var labelFactory = new FrameworkElementFactory(typeof(TextBlock));
var template = new HierarchicalDataTemplate(typeof(Node)) { ItemsSource = new Binding("Children") };
labelFactory.SetBinding(TextBlock.TextProperty, new Binding("Text"));
template.VisualTree = labelFactory;
treeView.ItemTemplate = template;

类型我绑定到:

public class Node
{
    public List<Node> Children { get; set; }

    public Node Parent { get; set; }

    public bool IsSelected { get; set; }
    public bool IsExpanded { get; set; }
}

实际绑定,正确显示层次结构所需的空白根:

var hierarchy = Helpers.GetHierarchy();
var rootNode = new Node();
rootNode.Children.Add(hierarchy);
GVSObjectStructureTreeView.ItemsSource = rootNode.Children;

需要以编程方式选择/扩展特定项目,但是当我这样做时

var itemToSelect = FindTreeViewItem(treeView.ItemsSource as List<Node>, elementId);
itemToSelect.IsSelected = true;

什么都没发生。扩展也一样。我想问题出在绑定上,但无法弄清楚。提前感谢您的帮助。

4

2 回答 2

2

重写服务类和问题得到解决。这是我实现的两个递归层次结构助手(可能对其他人有用):

 private static Node FindTreeViewItem(IEnumerable<Node> treeViewItems, string key)
 {
      if (treeViewItems == null) return null;
      foreach (var item in treeViewItems)
      {
         if (item.AssociatedObject.ID.Equals(key))
         {
            return item;
         }
         if (item.Children != null)
         {
            var childItem = FindTreeViewItem(item.Children, key);
            if (childItem != null)
            {
               return childItem;
            }
         }
      }
      return null;
 }

 private static void ExpandTreeViewItemParents(Node treeViewItem)
 {
     if (treeViewItem == null) return;
     if (treeViewItem.Parent != null)
     {
         treeViewItem.Parent.IsExpanded = true;
     }
     ExpandTreeViewItemParents(treeViewItem.Parent);
 }

在点击处理程序中使用如下:

var selectedItem = FindTreeViewItem(treeView.ItemsSource as List<Node>, ID);
if (selectedItem != null)
{
     selectedItem.IsSelected = true;
     ExpandTreeViewItemParents(selectedItem);
}
于 2012-05-05T11:33:49.627 回答
1

它看起来不像你的类implements INotifyPropertyChanged,所以即使绑定是正确的也不会发生任何事情,除非你为了简洁而省略了它。

于 2012-04-23T14:00:20.483 回答