WPF FAQ – Comment cocher les nœuds enfant d’un TreeView
-
lundi 28 juin 2010 13:22
Pour ce faire, on peut utiliser ‘data binding’. On peut créer une classe qui contient une propriété booléenne qui sera liée à la propriété IsChecked de CheckedBox et une propriété collection qui sera liée aux nœuds enfant de TreeViewItem. Quand l’état d’une CheckBox dans un TreeViewItem change, ses nœuds enfant changeront leur état par la propriété booléenne. Voici un exemple :
<Window.Resources> <HierarchicalDataTemplate DataType="{x:Type local:Node}" ItemsSource="{Binding Children}"> <StackPanel Orientation="Horizontal"> <CheckBox IsChecked="{Binding IsChecked}"/> <TextBlock Text="{Binding Text}"/> </StackPanel> </HierarchicalDataTemplate> </Window.Resources> <TreeView ItemsSource="{Binding Nodes, ElementName=Window}"/>public partial class MainWindow : Window { public MainWindow() { this.Nodes = new ObservableCollection<Node>() { new Node(){Text="Node A"}, new Node(){Text="Node B"}, }; this.Nodes[0].Children.Add(new Node() { Text = "Node C" }); this.Nodes[0].Children.Add(new Node() { Text = "Node D" }); this.Nodes[1].Children.Add(new Node() { Text = "Node E" }); this.Nodes[1].Children.Add(new Node() { Text = "Node F" }); InitializeComponent(); } public ObservableCollection<Node> Nodes { get; private set; } } public class Node : INotifyPropertyChanged { ObservableCollection<Node> children = new ObservableCollection<Node>(); string text; bool isChecked; public ObservableCollection<Node> Children { get { return this.children; } } public bool IsChecked { get { return this.isChecked; } set { this.isChecked = value; RaisePropertyChanged("IsChecked"); } } public string Text { get { return this.text; } set { this.text = value; RaisePropertyChanged("Text"); } } public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(string propertyName) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); if (propertyName == "IsChecked") { foreach (Node child in this.Children) child.IsChecked = this.IsChecked; } } } public class Container : INotifyPropertyChanged { bool isChecked; public bool IsChecked { get { return this.isChecked; } set { this.isChecked = value; RaisePropertyChanged("IsChecked"); } } public Node Node { get; set; } }Pour plusieurs informations sur WPF, consultez la page Formation WPF – Foire aux Questions

