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控件就可以實現數據綁定,并且可以在后臺動態添加數據。