我正在创建一个使用此XAML代码绑定到XML文件(或其他方式..)的WPF TreeView
<UserControl x:Class="XmlOutline.OutlineWindowControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:vsshell="clr-namespace:Microsoft.VisualStudio.Shell;assembly=Microsoft.VisualStudio.Shell.15.0"
Background="{DynamicResource {x:Static vsshell:VsBrushes.WindowKey}}"
Foreground="{DynamicResource {x:Static vsshell:VsBrushes.WindowTextKey}}"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Name="MyToolWindow">
<UserControl.Resources>
<XmlDataProvider x:Key="XmlProvider" Source="LogansTest.xml" XPath="/Items"/>
<HierarchicalDataTemplate x:Key="NodeTemplate" ItemsSource="{Binding XPath=./*}">
<TextBlock x:Name="nodetext"/>
<HierarchicalDataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=NodeType}" Value="Element">
<Setter TargetName="nodetext" Property="Text" Value="{Binding Path=Name}"/>
</DataTrigger>
</HierarchicalDataTemplate.Triggers>
</HierarchicalDataTemplate>
</UserControl.Resources>
<Grid x:Name="TreeGrid" DataContext="XmlProvider">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TreeView Name="TreeItems"
ItemTemplate="{StaticResource NodeTemplate}"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
ItemsSource="{Binding}"
VirtualizingStackPanel.IsVirtualizing="False"
VirtualizingStackPanel.VirtualizationMode="Standard">
</TreeView>
</Grid>
</UserControl>
我正在设置像这样的Xml上下文
var provider = new XmlDataProvider()
{
Source = new Uri(gotFocus.Document.Path + gotFocus.Document.Name), XPath = "./*"
};
OutlineWindowInstance.TreeItems.DataContext = provider;
然后我编辑Xml文件并保存我调用的更改
var prov = (XmlDataProvider) OutlineWindowInstance.TreeItems.DataContext;
prov.Refresh();
这更新树视图很棒,但它也会收缩所有节点,而不是记住IsExpanded状态。 我无法弄清楚如何让它记住这个状态,有人能指出我正确的方向吗? :)
答案 0 :(得分:0)
请尝试以下操作:
public Form1()
{
InitializeComponent();
TreeNode newNode1 = new TreeNode("Node 1");
treeView1.Nodes.Add(newNode1);
TreeNode newNode1a = new TreeNode("Node 1a");
newNode1.Nodes.Add(newNode1a);
treeView1.Click += new EventHandler(treeView1_Click);
TreeNode newNode2 = new TreeNode("Node 2");
treeView1.Nodes.Add(newNode2);
TreeNode newNode3 = new TreeNode("Node 3");
treeView1.Nodes.Add(newNode3);
}
void treeView1_Click(object sender, EventArgs e)
{
TreeView node = sender as TreeView;
if (node != null)
{
TreeNode selectedNode = node.SelectedNode;
string nodeName = selectedNode.Name;
Boolean expanded = selectedNode.IsExpanded;
}
}