2016-10-24 2 views
0

Создаю свои TreeViewItems с классом Node. В примере узлы указаны в исходном коде. Но как это сделать, если узлы должны быть импортированы из текстового файла с содержимым, как это:C# WPF: Создать TreeView из текстового файла

text file content

Любые идеи?

Я пробовал следующее.

public MainWindowVM() 
    { 
     private ObservableCollection<Node> mRootNodes; 
     public IEnumerable<Node> RootNodes { get { return mRootNodes; } } 
     List<string[]> TreeNodes = new List<string[]>(); 

     string[] lines = null; 
     try 
     { 
      lines = System.IO.File.ReadAllLines(MainWindow.TextFilePath , System.Text.Encoding.Default); 
     } 
     catch (IOException ex) 
     { 
      MessageBox.Show(ex.Message); 
      Environment.Exit(0); 
     } 
     if (lines == null || lines.Length == 0) 
     { 
      MessageBox.Show("Text file has no content!"); 
      Environment.Exit(0); 
     } 

     foreach (var line in lines) 
     { 
      TreeNodes.Add(line.Split('|')); 
     } 

     Node newNode = null; 
     Node childNode = null; 
     Node root = new Node() { Name = TreeNodes[0][0] }; 
     if (TreeNodes[0].Length > 1) 
     { 
      newNode = new Node() { Name = TreeNodes[0][1] }; 
      root.Children.Add(newNode); 
     } 
     for (int s = 2; s < TreeNodes[0].Length; s++) 
     { 
      childNode = new Node() { Name = TreeNodes[0][s] }; 
      newNode.Children.Add(childNode); 
      newNode = childNode; 
     } 
    } 

но я получаю только первые два узла. Я не знаю, как построить весь TreeView с помощью цикла.

TreeView

+1

мне особенно нравится идея размещения * текстовый файл * содержание, как * Скриншот *. Можете ли вы разместить его как ** текст **, а также включить код класса «Node» в вопрос (ссылка неверна) – ASh

+0

, пожалуйста, нажмите на верхнюю часть «Узел». Я исправил ссылку. – sanjar14

ответ

0

входной пример

Root|A 
Root|B|C 
Root|B|D 
Root|E 

проблема с вашим кодом является то, что вы только обрабатывать TreeNodes[0] элемент. обработать коллекцию элементов вам нужно петля,

public MainWindowVM() 
{ 
    private ObservableCollection<Node> mRootNodes; 
    public IEnumerable<Node> RootNodes { get { return mRootNodes; } } 

    string[] lines = null; 
    try 
    { 
     lines = System.IO.File.ReadAllLines(MainWindow.TextFilePath , System.Text.Encoding.Default); 
    } 
    catch (IOException ex) 
    { 
     MessageBox.Show(ex.Message); 
     Environment.Exit(0); 
    } 
    if (lines == null || lines.Length == 0) 
    { 
     MessageBox.Show("Text file has no content!"); 
     Environment.Exit(0); 
    } 
Dictionary<string, Node> nodeCache = new Dictionary<string, Node>(); 
    // processing each line 
    foreach (var line in lines) 
    {     
     Node parentNode = null; 
     string key = null; 
     // in each line there are one or more node names, separated by | char 
     foreach (string childNodeName in line.Split('|')) 
     { 
      Node childNode; 
      // names are not unique, we need a composite key (full node path) 
      key += "|" + childNodeName; 
      // each node has unique key 
      // if key doesn't exists in cache, we need to create new child node 
      if (false == nodeCache.TryGetValue(key, out childNode)) 
      { 
       childNode = new Node { Name = childNodeName }; 
       nodeCache.Add(key, childNode); 

       if (parentNode != null) 
        // each node (exept root) has a parent 
        // we need to add a child node to parent ChildRen collection 
        parentNode.Children.Add(childNode); 
       else 
        // root nodes are stored in a separate collection 
        mRootNodes.Add(childNode); 
      } 

      // saving current node for next iteration 
      parentNode = childNode; 
     } 
    } 
} 
+0

Работает отлично. Спасибо – sanjar14

+0

Другое дело: узлы с тем же именем должны быть разрешены. Как это сделать со словарем? Пример: Корень | A Корень | B | C Корень | B | D – sanjar14

+0

@ sanjar14, если имя не уникально, то это не может быть ключом. Я создал составной ключ для узлов. см. мое редактирование – ASh

Смежные вопросы