【问题标题】:Find and refresh treeview from popup window从弹出窗口中查找和刷新树视图
【发布时间】: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


【解决方案1】:

不幸的是,您不能使用弹出窗口在可视树上上下移动,因为弹出窗口不是可视树的一部分。 DataBinding 也是如此,popup 不会从树中继承绑定。

我使用Josh Smith's DataContextSpy 类/示例来实例化弹出窗口所需的部分绑定,并将其作为StaticResource 分配给弹出窗口。然后在弹出窗口中直接操作 DataContext ,间接操作应用程序的其他部分(在您的情况下 - 可视化树)。

或者您可以选择将部分控件公开为公共属性方法,并允许它们之间更紧密的耦合..

【讨论】:

    猜你喜欢
    • 2015-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 2011-05-15
    相关资源
    最近更新 更多