Bind Any XML document to WPF TreeView

后端 未结 3 366
长发绾君心
长发绾君心 2021-01-02 17:01

I would like to bind any XML document to WPF TreeView using TypeConverter.

My original solution was to use recursion, but when document is large UI is heavily tied u

3条回答
  •  一整个雨季
    2021-01-02 17:33

    So I have asked a question on how to bind any XML document regardless of schema to tree view in the following way: 1. Bind XML Document to WPF TreeView via XML Provider and HierarchicalDataTemplate. 2. Display all nodes of the XML Document including those that have child nodes in following format:

    >Node1

    Node1 Contents

        >ChildNode1
    
           ChildNode1 Contents
    
                >ChildNode1'sChildNode
    
                  ChildNode1'sChildNode Contents
    

    >Node2

      Node2 Contents
    

    Problem was that my TreeView was binding each XmlNode name property to TreeItem. In case of text XmlNode it would bind #text to the TreeItem which was not what I wanted.

    So via a post on MSDN forum I got my answer: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/cbdb2420-1403-436f-aa7f-b1e3b1acb398/

    So the trick was to use triggers to set value based on type of node encountered.

    Caveat is that other types of nodes will be ignored and XML document may contain diffrent elements, so this might not work for every type of node encountered.

    Here's XAML:

    
    
    
        
            
            
                
            
            
                
                    
                
                
                    
                
                        
        
        
    
    
    
        
    
    

    public Window1()
    {
    InitializeComponent();
    XmlDataProvider dataProvider = this.FindResource("xmlDataProvider") as XmlDataProvider;
            XmlDocument doc = new XmlDocument();
                // Testdocument        doc.LoadXml(
                @"
                    text1text11
                    
                    text2text21
                        text22
                    
                  ");
            dataProvider.Document = doc;
        }
    

提交回复
热议问题