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控件就可以实现数据绑定,并且可以在后台动态添加数据。