WPF:动态构建树

时间:2013-06-05 13:39:46

标签: wpf

我想通过从下面的方法调用root和child来构建动态树。 我有一个TransactionTypeViewModel,它有3个方法

tranViewModel.GetWSMethodName()
tranViewModel.GetAllRequest()
tranViewModel.GetAllResponse()

我有这个字符串列表,我需要通过方法循环并将项目添加到我的字符串列表中: 字符串将用于显示树的根和子。

List<String> wsMethodNameList = new List<String>();   // root of tree  from tranViewModel.GetWSMethodName()
List<String> requestXmlList = new List<String>();      // child1  tranViewModel.GetAllRequest()
List<String> responseXmlList = new List<String>();     // child2  tranViewModel.GetAllResponse()

一旦我从每个方法中获取字符串列表,我就想构建我的树。

List<TreeViewModel> nodes = getAllTreeNodesFromModel();
        var request = new TreeViewModel();
        var response = new TreeViewModel();
        var parent = new TreeViewModel();

        List<TreeViewModel> requestNodes = new List<TreeViewModel>();

        for (int i = 0; i < requestXmlList.Count; i++)
        {
           // requestNodes = new List<TreeViewModel>();
            request = new TreeViewModel { Value = requestXmlList[i] };
            //requestNodes.Add(request);
            request.Children = nodes;
        }


        List<TreeViewModel> responseNodes = new List<TreeViewModel>();
        for (int i = 0; i < responseXmlList.Count; i++)
        {
           // responseNodes = new List<TreeViewModel>();
            response = new TreeViewModel { Value = responseXmlList[i] };
            // responseNodes.Add(response);
            response.Children = nodes;
        }

        List<TreeViewModel> parentNode = new List<TreeViewModel>();
        for (int i = 0; i < wsMethodNameList.Count; i++)
        {

           // parentNode = new List<TreeViewModel>();
            parent = new TreeViewModel { Value = wsMethodNameList[i] };
          //  parentNode.Add(parent);
            parent.Children.Add(request);
            parent.Children.Add(response);

        }

        return new ObservableCollection<TreeViewModel> { parent };

在我执行完毕后,我得到的是重复的树视图。我找不到更简单的方法来解决这个问题。有人可以帮我理解吗?

1 个答案:

答案 0 :(得分:0)

我想我发现了问题所在。我正在为每个列表创建循环。这是我如何清理它:

       for (int i = 0; i < wsMethodNameList.Count; i++)
        {
            var child = new TreeViewModel { Value = wsMethodNameList[i] };
            parent.Children.Add(child);

            var requestChild = new TreeViewModel { Value = requestXmlList[i] };

            requestChild.Children = nodes;
            child.Children.Add(requestChild);


            var responseChild = new TreeViewModel { Value = responseXmlList[i] };

            responseChild.Children = nodes;
            child.Children.Add(responseChild);               

        }

        return new ObservableCollection<TreeViewModel> { parent };