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