IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

[WPF] Comment créer une treeview avec des items custom?


Sujet :

C#

  1. #1
    Membre éclairé Avatar de -N4w4k-
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2011
    Messages
    545
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Haute Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : Industrie

    Informations forums :
    Inscription : Novembre 2011
    Messages : 545
    Points : 801
    Points
    801
    Par défaut [WPF] Comment créer une treeview avec des items custom?
    Bonjour,

    Je me met à apprendre le WPF et aujourd'hui j'essaie de faire une treeview custom, afin d'afficher des objets à moi. J'ai un peu de mal à comprendre comment manipuler les templates (HierarchicalDataTemplate, DataTemplate, ItemTemplate, etc...).

    Voici les objets que je veux représenter:

    MyTreeNode.cs
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
        public class MyTreeNode    {
            private string text;
            private ObservableCollection<MyTreeNode> items;
            private ObservableCollection<MyTreeNodeAttribute> attributes;
     
     
            public string Text
            {
                get { return this.text; }
                set { this.text = value; }
            }
     
     
            public ObservableCollection<MyTreeNode> Items
            {
                get
                {
                    if (this.items == null)
                        this.items = new ObservableCollection<MyTreeNode>();
                    return items;
                }
            }
     
     
            public ObservableCollection<MyTreeNodeAttribute> Attributes
            {
                get
                {
                    if (this.attributes == null)
                        this.attributes = new ObservableCollection<MyTreeNodeAttribute>();
                    return attributes;
                }
            }
     
     
            public MyTreeNode() { }
     
     
            public MyTreeNode(string text)
            {
                this.Text = text;
            }
     
     
            public MyTreeNode(string text, params string[] attributes)
            {
                this.Text = text;
     
     
                foreach (string[] attr in attributes.Where(x => x.Contains(':')).Select(x => x.Split(':')))
                    this.Attributes.Add(new MyTreeNodeAttribute(attr[0], attr[1]));
            }
        }
    MyTreeNodeAttribute.cs
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
        public class MyTreeNodeAttribute    {
            public string Key { get; set; }
            public string Value { get; set; }
     
     
            public MyTreeNodeAttribute() { }
     
     
            public MyTreeNodeAttribute(string key, string value)
            {
                this.Key = key;
                this.Value = value;
            }
        }
    Et voici le xaml que j'ai (qui n'affiche que la propriété Text de mes MyTreeNode pour le moment):
    Code xaml : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    <TreeView x:Class="Test_TreeView_2.Tree.MyTreeView"            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                xmlns:tree="clr-namespace:Test_TreeView_2.Tree"
                mc:Ignorable="d" 
                d:DesignHeight="300"
                d:DesignWidth="300">
        <TreeView.Resources>
            <ResourceDictionary>
                <HierarchicalDataTemplate ItemsSource="{Binding Items}" DataType="{x:Type tree:MyTreeNode}" >
                        <TextBlock Text="{Binding Text}" />
                </HierarchicalDataTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Attributes}" DataType="{x:Type tree:MyTreeNodeAttribute}">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="150"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>
                        <TextBlock Grid.Column="0" Text="{Binding Key}" />
                        <TextBlock Grid.Column="1" Text="{Binding Value}" />
                    </Grid>
                </HierarchicalDataTemplate>
            </ResourceDictionary>
        </TreeView.Resources>
    </TreeView>


    J'aimerais avoir le résultat suivant:

    • Item.Text

    ​Attribute.Key Attribute.Value
    ​Attribute.Key Attribute.Value
    ​Attribute.Key Attribute.Value

    • Item.Text

    ​Attribute.Key Attribute.Value
    ​Attribute.Key Attribute.Value
    ​Attribute.Key Attribute.Value

    • Item.Text

    ​Attribute.Key Attribute.Value
    ​Attribute.Key Attribute.Value
    ​Attribute.Key Attribute.Value

    • Item.Text

    ​Attribute.Key Attribute.Value
    ​Attribute.Key Attribute.Value
    ​Attribute.Key Attribute.Value

    • Item.Text

    ​Attribute.Key Attribute.Value
    ​Attribute.Key Attribute.Value
    ​Attribute.Key Attribute.Value

    • Item.Text

    ​Attribute.Key Attribute.Value
    ​Attribute.Key Attribute.Value
    ​Attribute.Key Attribute.Value
    Je pense que je suis pas très loin de la solution mais je sais pas comment faire pour afficher les attributs des items en plus de la propriété Text.

    Auriez vous une piste?
    J’ai des questions à toutes vos réponses!

  2. #2
    Expert confirmé
    Inscrit en
    Avril 2008
    Messages
    2 564
    Détails du profil
    Informations personnelles :
    Âge : 64

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 441
    Points
    4 441
    Par défaut
    bonjour

    Ton "treenode" est mal fichu....
    1/Un TreeNode est simplement un tree ou arbre ....
    2/sa liste d'enfants ou child est unique consitue de "treenodes"
    3/chaque enfant "treenode" peut avoir bien des sous-enfants de type "attribut"...
    Bien sur cette structure etant recursive rien n'empeche que chaque "attribut" ait lui-meme une liste d'enfants (what ever you want) ..recursivement....
    ton code du treenode doit revu comme suit :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Collections.ObjectModel;
     
    namespace WpfTestBogus
    {
        //attribut du node
        public class MyNodeAttribute
        {
            public string Key { get; set; }
            public string Value { get; set; }
     
     
            public MyNodeAttribute() 
            { }
     
     
            public MyNodeAttribute(string key, string value)
            {
                this.Key = key;
                this.Value = value;
            }
        }
        //le node
        public class MyNode
        {
            private string text;
            public string Text
            {
                get { return this.text; }
                set { this.text = value; }
            }
            private ObservableCollection<MyNodeAttribute> attributes;
            public ObservableCollection<MyNodeAttribute> Attributes
            {
                get
                {
                    if (this.attributes == null)
                        this.attributes = new ObservableCollection<MyNodeAttribute>();
                    return attributes;
                }
            }
     
     
            public MyNode() { }
            public MyNode(string text)
            {
                this.Text = text;
            }
     
     
            public MyNode(string text, params string[] attributes)
            {
                this.Text = text;
     
     
                foreach (string[] attr in attributes.Where(x => x.Contains(':')).Select(x => x.Split(':')))
                    this.Attributes.Add(new MyNodeAttribute(attr[0], attr[1]));
            }
        }
        //le "tree" des nodes
        public class MyTreeNode
        {
            public MyTreeNode()
            {
                this.text = "My TreeNode";
                mynodes = new ObservableCollection<MyNode>();
     
            }
            public MyTreeNode(string text)
                : this()
            {
                this.Text = text;
            }
            private string text;
            public string Text
            {
                get { return this.text; }
                set { this.text = value; }
            }
            private ObservableCollection<MyNode> mynodes;
            public ObservableCollection<MyNode> MyNodes
            {
                get { return mynodes; }
                set { this.mynodes = value; }
            }
        }
    }
    Ensuite ton custom control "MyTreeView" doit avoir ses resources dans un Dictionnary avec "cle" dans app.xaml...la cle est exigible car plusieurs dictionaries peuvent y figurer....
    Cela permet d'initialiser correctement les DataTemplates au chargement de l'application avant de charger ton custom control...

    code du resource DictionaryMyTreeView.xaml:
    Code xaml : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                        xmlns:local="clr-namespace:WpfTestBogus" >
        <!--style pour "voir" le TreeViewItem "expanded-->
        <Style TargetType="TreeViewItem">
            <Setter Property="IsExpanded" Value="true"/>
        </Style>
        <!--les DataTemplates  necessaires suivent -->
        <HierarchicalDataTemplate 
            DataType="{x:Type local:MyTreeNode}"
            ItemsSource="{Binding MyNodes}" >
            <TextBlock 
                Width="100" Foreground="Red" 
                FontFamily="Arial"
                FontSize="14"
                FontWeight="Bold" 
                Text="{Binding Text}" />
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate 
            DataType="{x:Type local:MyTreeNode}"
            ItemsSource="{Binding MyNodes}" >
            <TextBlock 
                Width="100" Foreground="Red" 
                FontFamily="Arial"
                FontSize="14"
                FontWeight="Bold" 
                Text="{Binding Text}" />
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate  
            DataType="{x:Type local:MyNode}"
            ItemsSource="{Binding Attributes}" >
            <TextBlock 
                Width="100" Foreground="Black"  
                FontFamily="Arial"
                FontSize="12"
                FontWeight="Bold" 
                Text="{Binding Text}"/>
        </HierarchicalDataTemplate >
        <DataTemplate
            DataType="{x:Type local:MyNodeAttribute}"
            >
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="150"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <TextBlock Grid.Column="0" Background="LightPink"    Text="{Binding Key}" />
                <TextBlock Grid.Column="1" Background="LightBlue"  Text="{Binding Value}" />
            </Grid>
        </DataTemplate>
     
    </ResourceDictionary>

    code de app.xaml
    Code xaml : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    <Application x:Class="WpfTestBogus.App"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:local="clr-namespace:WpfTestBogus" 
                 StartupUri="MainWindow.xaml">
        <Application.Resources>
            <ResourceDictionary 
                x:Key="dico1"
               Source="Dictionary1.xaml">
     
            </ResourceDictionary>
            <ResourceDictionary 
                x:Key="dico2"
               Source="DictionaryMyTreeView.xaml">
            </ResourceDictionary>
        </Application.Resources>
    </Application>

    code behind .cs du simplistic MyTreeView:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
     
    namespace WpfTestBogus
    {
        /// <summary>
        /// Logique d'interaction pour MyTreeView.xaml
        /// </summary>
        public partial class MyTreeView : TreeView
        {
            public MyTreeView()
            {
                InitializeComponent();
            }
        }
    }
    Et plus simplistic code xaml:
    Code xaml : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
    <TreeView x:Class="WpfTestBogus.MyTreeView"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
                 mc:Ignorable="d" 
               xmlns:local="clr-namespace:WpfTestBogus" 
              d:DesignHeight="300" d:DesignWidth="300"
              Resources="{StaticResource dico2}">
        <!--note la reference au dictionary-->
    </TreeView>

    code behind .cs du class de test qui "populate" le treenode .C'est SIMPLEMENT un ObservableCollection<MyTreeNode> qui contient notre treenode...
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Collections.ObjectModel;
     
    namespace WpfTestBogus
    {
        //class de test de type ObservableCollection<MyTreeNode>
        //contient un seul "Tree"
        public class TestTree : ObservableCollection<MyTreeNode> 
        {
           MyTreeNode treeNode =null ;
           MyNode nd;
           string[] attr=new string [3];
           public TestTree()
           {
               treeNode = new MyTreeNode("My TreeNode");
     
               for (int i = 0; i < 10; i++)
               {
                   for (int j = 0; j < attr.Length; j++)
                   {
                       attr[j]="Key"+j.ToString()+":"+"Value"+j.ToString();
                   }
     
     
                   nd = new MyNode("Item" + i.ToString(), attr);
                   treeNode.MyNodes.Add (nd);
               }
               this.Add(treeNode);
     
           }
        }
    }
    et finalement le code xaml du mainwindow qui utilise le cust control et le Tree:

    Code xaml : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <Window x:Class="WpfTestBogus.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfTestBogus" 
            Title="MainWindow" Height="350" Width="525">
        <Window.Resources>
            <local:TestTree  x:Key="data"></local:TestTree>
        </Window.Resources>
        <Grid>
            <local:MyTreeView
                ItemsSource="{Binding Source={StaticResource data}}">
            </local:MyTreeView>
        </Grid>
    </Window>
    bon code..............

  3. #3
    Membre éclairé Avatar de -N4w4k-
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2011
    Messages
    545
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Haute Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : Industrie

    Informations forums :
    Inscription : Novembre 2011
    Messages : 545
    Points : 801
    Points
    801
    Par défaut
    Salut MABROUKI, et merci d'avoir pris le temps de me répondre. J'ai essayé de faire un projet test avec ton code mais malheureusement j'ai eu exception sur exception. Cependant, je pense avoir compris ce que tu voulais me montrer, et comment le faire. En fait mon problème se trouve à un autre endroit, j'ai surement pas bien expliqué dans mon premier post..

    Dans ton exemple, tu as un objet MyTreeNode qui contient une collection de MyNode, donc sur 2 niveaux, or j'aimerais avoir 1 seul type d'objet sur plusieurs niveaux:

    -node
    -node
    -node
    -node
    -node
    -node
    -node
    -node
    -node
    -node
    -node
    -node
    -node
    -node
    -node
    Et la difficulté que j'ai, c'est pour afficher les attributs d'un noeud dans la treeview:

    Code xaml : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
        <TreeView.Resources>
            <ResourceDictionary>
                <HierarchicalDataTemplate DataType="{x:Type tree:MyTreeNode}" ItemsSource="{Binding Nodes}" >
                    <TextBlock Text="{Binding Text}" />
                    <!-- 
    Je voudrais afficher les attributs du noeud ici.. 
     
    -text: attributes
        -text: attributes
        -text: attributes
        -text: attributes
            -text: attributes
    -text: attributes
        -text: attributes
     -->
                </HierarchicalDataTemplate>
                <DataTemplate DataType="{x:Type tree:MyTreeNodeAttribute}" >
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="150"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>
                        <TextBlock Grid.Column="0" Text="{Binding Key}" />
                        <TextBlock Grid.Column="1" Text="{Binding Value}" />
                    </Grid>
                </DataTemplate>
            </ResourceDictionary>
        </TreeView.Resources>

    J'espère avoir exposer mon problème plus clairement..
    J’ai des questions à toutes vos réponses!

  4. #4
    Membre averti
    Homme Profil pro
    Directeur de projet
    Inscrit en
    Novembre 2014
    Messages
    196
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Côte d'Or (Bourgogne)

    Informations professionnelles :
    Activité : Directeur de projet
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2014
    Messages : 196
    Points : 331
    Points
    331
    Par défaut
    HierachicalDataTemplate est fait pour afficher une hierarchie d'objet. Il ne faut donc pas ecrire la hiérarchie de ton TreeView a l'intérieur de ce template mais uniquement la representation graphique d'un noeud. Les enfants du noeud créer c'est le framework qui les cré. Pour ce faire il regarde la propriété ItemsSource du HierarchicalDataTemplate, il trouve le type des éléments de la collection et recherche dans les ressources de l'application un template pour ce type d'objet. Si le template trouvé est un DataTemplate normal s'arrete a ce niveau (en affichant le template) si c'est de nouveau un HierarchicalDataTemplate il recommence, et comme cela a l'infini (en théorie)

  5. #5
    Expert confirmé
    Inscrit en
    Avril 2008
    Messages
    2 564
    Détails du profil
    Informations personnelles :
    Âge : 64

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 441
    Points
    4 441
    Par défaut
    bonjour
    Oups !!! J'ai mal compris le souci....
    En fait ton "treeview custom" est à modifier un tout petit seulement ....dans ses "resources" pour y inclure un ListBox qui afficheras les "atrributes" ....
    Le code des datas se simplifie car ton node est "recursif" puisque il fait reference à sa propre liste "nodes"...
    Bref code .cs du class "mynode":
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
     //attribut du node
        public class MyNodeAttribute
        {
            public string Key { get; set; }
            public string Value { get; set; }
     
     
            public MyNodeAttribute()
            { }
            public MyNodeAttribute(string key, string value)
                : this()
            {
                this.Key = key;
                this.Value = value;
            }
        }
        //le node
        public class MyNode
        {
            public MyNode()
            {
                this.attributes = new ObservableCollection<MyNodeAttribute>();
                this.nodes = new ObservableCollection<MyNode>();
            }
            public MyNode(string text)
                :this()
            {
                this.Text = text;
            }
            public MyNode(string text, params string[] attributes)
                : this()
            {
                this.Text = text;
                foreach (string[] attr in attributes.Where(x => x.Contains(':')).Select(x => x.Split(':')))
                    this.attributes.Add(new MyNodeAttribute(attr[0], attr[1]));
            }
            private string text;
            public string Text
            {
                get { return this.text; }
                set { this.text = value; }
            }
            private ObservableCollection<MyNodeAttribute> attributes;
            public ObservableCollection<MyNodeAttribute> Attributes 
            {
                get { return attributes ;}
                set { attributes=value ;}
            }
     
            private ObservableCollection<MyNode> nodes;
            public ObservableCollection<MyNode> Nodes
            {
                get { return nodes; }
                set { nodes = value; }
            }
     
     
        }
    code .cs du class de test qui cree le tree .C'est SIMPLEMENT un ObservableCollection<MyTreeNode> qui contient un seul MyNode qui sert de noeud parent "racine"...

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Collections.ObjectModel;
     
    namespace WpfCustomTreeView
    {
        //ce class de test est de type ObservableCollection<MyTreeNode>
        //pour faire directement le test en xaml 
        //on lui ajoute un seul "Tree"
        public class TestTree : ObservableCollection<MyNode>
        {
            MyNode treeNode = null;
            MyNode node = null;
            string[] attr = new string[3];
            int maxLevel = 3;
            int levelCount;
            int nbChild = 2;
            public TestTree()
            {
                for (int j = 0; j < attr.Length; j++)
                {
                    attr[j] = "Key" + j.ToString() + ":" + "Value" + j.ToString();
                }
     
                treeNode = new MyNode("My TreeNode", attr);
                levelCount = 0;
                AddNodes(treeNode, levelCount);
                this.Add(treeNode);
     
            }
            private void AddNodes(MyNode nodeStart, int lvl)
            {
                if (lvl > maxLevel) return;
                AddNode(nodeStart, lvl + 1);
     
                foreach (MyNode item in nodeStart.Nodes)
                {
                    AddNodes(item, lvl + 1);
                }
     
            }
            private void AddNode(MyNode node, int lvl)
            {
     
                for (int i = 0; i < nbChild; i++)
                {
                    node.Nodes.Add(new MyNode("ChildNode" + lvl.ToString(), attr));
                }
     
            }
        }
    }
    Code xaml de ton "treeview custom":

    Code xaml : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    <TreeView x:Class="WpfCustomTreeView.MyTreeView"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
          xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
          xmlns:local="clr-namespace:WpfCustomTreeView"
            mc:Ignorable="d" 
          d:DesignHeight="300" d:DesignWidth="300"
    	>
        <TreeView.Resources>
            <Style TargetType="TreeViewItem">
                <Setter Property="IsExpanded" Value="true"/>
            </Style>
            <!--les DataTemplates  necessaires suivent -->
            <HierarchicalDataTemplate 
            DataType="{x:Type local:MyNode}"
            ItemsSource="{Binding Nodes}" >
                <StackPanel>
                    <TextBlock 
                    Width="100" Foreground="Red" 
                    FontFamily="Arial"
                    FontSize="14"
                    FontWeight="Bold" 
                    Text="{Binding Text}" />
                    <!--ici le listbox incorpore-->
                    <!--remarque comme "il sait retrouver le DataTemplate des attributes malgre l'absence du "key" "-->
                    <ListBox
                    ItemsSource="{Binding Path=Attributes}">
                        <ListBox.ItemsPanel>
                            <ItemsPanelTemplate>
                                <StackPanel Orientation="Vertical"  IsItemsHost="True" />
                            </ItemsPanelTemplate>
                        </ListBox.ItemsPanel>
                    </ListBox>
                </StackPanel>
     
            </HierarchicalDataTemplate>
            <DataTemplate
            DataType="{x:Type local:MyNodeAttribute}">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="150"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Column="0" Foreground="Yellow"  Background="LightPink"    Text="{Binding Key}" />
                    <TextBlock Grid.Column="1" Background="LightBlue"  Text="{Binding Value}" />
                </Grid>
            </DataTemplate>
        </TreeView.Resources>
    </TreeView>

    le code xaml du Form de test :
    Code xaml : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <Window x:Class="WpfCustomTreeView.WinTestMyTreeView"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
           xmlns:local="clr-namespace:WpfCustomTreeView"
            Title="TestMyTreeView" Height="300" Width="300">
        <Window.Resources>
            <local:TestTree x:Key="data"></local:TestTree>
        </Window.Resources>
        <Grid>
            <local:MyTreeView
                ItemsSource="{Binding Source={StaticResource data}}">
            </local:MyTreeView>
        </Grid>
    </Window>

    Au final c'etait plus simple que prevu......
    bon code...

Discussions similaires

  1. Réponses: 6
    Dernier message: 18/07/2014, 13h21
  2. Comment créer une vue avec des paramètres (objets) ?
    Par Ryu2000 dans le forum Eclipse Platform
    Réponses: 25
    Dernier message: 12/12/2012, 13h11
  3. comment créer une video avec des images tif
    Par omarooo dans le forum Images
    Réponses: 1
    Dernier message: 12/10/2011, 12h07
  4. comment créer une application avec des switchs
    Par abderrahim_05 dans le forum Débuter
    Réponses: 5
    Dernier message: 28/12/2007, 19h07
  5. [PHP-JS] Comment créer une boucle avec des headers
    Par djinnwatcher dans le forum Langage
    Réponses: 10
    Dernier message: 17/07/2006, 15h48

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo