且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

TreeView:如何以编程方式将新的Child节点添加到WPF C中的选定节点#

更新时间:2023-10-13 15:28:28

请参阅:

https://msdn.microsoft.com/en-us/library/system.windows。 controls.treeviewitem%28v = vs.110%29.aspx [ ^ ],

https://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol。 items%28v = vs.110%29.aspx [ ^ ],

https://msdn.microsoft.com/en-us/library/system .windows.controls.itemcollection%28v = vs.110%29.aspx [ ^ ],

https://msdn.microsoft.com/en-us/library/ms589116(v = vs.110)的.aspx [ ^ ]。



现在,让我们按照这些帮助页面进行操作。从头开始创建WPF应用程序并将一些示例代码添加到主窗口。这是一个完整的文件:

Please see:
https://msdn.microsoft.com/en-us/library/system.windows.controls.treeviewitem%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.items%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/system.windows.controls.itemcollection%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/ms589116(v=vs.110).aspx[^].

Now, let's follow these help pages. Create a WPF application from scratch and add some sample code to main window. This is a complete file:
using System.Windows;
using System.Windows.Controls;

namespace SampleApplication.Ui {

    public partial class MainWindow : Window {

        public MainWindow() {
            // InitializeComponent(); // not really needed,
            // because this sample is fully programmatical;
            // you don't even need XAML if you properly write
            // your entry-point method (Main)
            TreeView treeView = new TreeView();
            TreeViewItem top = new TreeViewItem();
            top.Header = "sample header";
            TreeViewItem child = new TreeViewItem();
            child.Header = "sample child";
            TreeViewItem grandchild = new TreeViewItem();
            grandchild.Header = "sample grandchild";
            treeView.Items.Add(top);
            top.Items.Add(child);
            child.Items.Add(grandchild);
            this.AddChild(treeView);
        } //MainWindow

    } //class MainWindow

} //namespace SampleApplication.Ui



但实际上,这不是很典型的用法。在大多数情况下,您需要学习数据绑定。例如,请参阅 http://www.wpf-tutorial.com/treeview -control / treeview-data-binding-multiple-templates [ ^ ]。



另请参阅此更高级的CodeProject文章:使用ViewModel模式简化WPF TreeView [ ^ ]。



-SA


In practice, however, this is not very typical usage. In most cases, you need to learn data binding. See, for example, http://www.wpf-tutorial.com/treeview-control/treeview-data-binding-multiple-templates[^].

See also this more advanced CodeProject article: Simplifying the WPF TreeView by Using the ViewModel Pattern[^].

—SA