WPF中TreeView控件的数据绑定和后台动态添加数据可以通过以下步骤实现:
<TreeView x:Name="MyTreeView" ItemsSource="{Binding TreeData}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
public class TreeNode
{
public string Name { get; set; }
public ObservableCollection<TreeNode> Children { get; set; }
}
public class ViewModel
{
public ObservableCollection<TreeNode> TreeData { get; set; }
public ViewModel()
{
// 初始化数据源
TreeData = new ObservableCollection<TreeNode>
{
new TreeNode
{
Name = "Parent 1",
Children = new ObservableCollection<TreeNode>
{
new TreeNode { Name = "Child 1" },
new TreeNode { Name = "Child 2" }
}
},
new TreeNode
{
Name = "Parent 2",
Children = new ObservableCollection<TreeNode>
{
new TreeNode { Name = "Child 3" },
new TreeNode { Name = "Child 4" }
}
}
};
}
}
public MainWindow()
{
InitializeComponent();
// 设置数据上下文
DataContext = new ViewModel();
// 动态添加数据
TreeNode newNode = new TreeNode { Name = "New Node" };
((ViewModel)DataContext).TreeData.Add(newNode);
}
通过以上步骤,TreeView控件就可以实现数据绑定,并且可以在后台动态添加数据。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: wpf多个页面之间切换的方法是什么