【发布时间】:2014-01-14 14:12:53
【问题描述】:
我有一个问题。我在 WPF 项目中使用 TreeView 来可视化我的 XML 数据。 TreeView 位于 UserControl 中并链接到主网格。问题是,当我在弹出窗口中编辑我的 XML 数据时,我找不到树视图(按名称的元素)来刷新它。
请帮助我。
谢谢
WPF 主窗口:
...
...
<Grid>
<uc:UserControlTreeView/>
</Grid>
...
...
用户控制:
<UserControl x:Class="UserControlTreeView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<UserControl.Resources>
<XmlDataProvider x:Key="MyList" x:Name="MyList" Source="d:/a/library.xml" XPath="Libraries/*"/>
<HierarchicalDataTemplate DataType="Library" ItemsSource="{Binding XPath=*}">
<TextBlock Text="{Binding XPath=@Name}"></TextBlock>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="Batch" ItemsSource="{Binding XPath=*}">
<TextBlock Text="{Binding XPath=@Name}"></TextBlock>
</HierarchicalDataTemplate>
</UserControl.Resources>
<TreeView x:Name="libraryTree" VerticalAlignment="Top" AllowDrop="True" TreeViewItem.Expanded="TreeViewItem_Expanded" ItemsSource="{Binding Source={StaticResource MyList}}">
<TreeView.Resources>
<ContextMenu x:Key="TestMenu">
</ContextMenu>
</TreeView.Resources>
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded" Value="False"/>
<EventSetter Event="PreviewMouseRightButtonDown" Handler="OnPreviewMouseRightButtonDown" />
</Style>
</TreeView.ItemContainerStyle>
</TreeView>
</UserControl>
和小窗口的代码:
XmlElement root = docx.DocumentElement; XmlNode element = root.SelectSingleNode("/Libraries/Library[@Name='Pics']");
XmlElement child = docx.CreateElement("Batch");
child.SetAttribute("Name", System.IO.Path.GetFileName(fname));
child.SetAttribute("Type", "Batch");
child.SetAttribute("Path", fname);
element.AppendChild(child);
docx.Save("d:/a/library.xml");
TreeView tr = (TreeView)Application.Current.MainWindow.FindName("libraryTree");
//TreeView tr = (TreeView)this.Owner.FindName("libraryTree");
tr.Items.Refresh();
tr.UpdateLayout();
但是 tr 仍然是 null :(
【问题讨论】:
-
快速而肮脏的方法可能是在 MainWindow 中实现一个公共方法来刷新树视图(它应该能够通过其私有变量名称访问 TreeView)。但是,只要只涉及文件系统 uri,更好的方法是执行此博客中解释的类似操作:WPF - Updating XmlDataProvider when source XML changes。
-
是的,这正是我所需要的。谢谢。
标签: c# wpf treeview find element