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

Windows Presentation Foundation Discussion :

Comment ouvrir un élément d'arborescence d'un TreeView ?


Sujet :

Windows Presentation Foundation

  1. #1
    Membre à l'essai
    Homme Profil pro
    Consultant informatique
    Inscrit en
    Septembre 2011
    Messages
    10
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Consultant informatique
    Secteur : Finance

    Informations forums :
    Inscription : Septembre 2011
    Messages : 10
    Points : 14
    Points
    14
    Par défaut Comment ouvrir un élément d'arborescence d'un TreeView ?
    Bonjour

    Je travaille sous WPF et je veux utiliser un TreeView pour afficher les dossiers d'une manière presque similaire à l'Explorateur Windows
    J'affiche la TreeView avec les Items que je peux étendre ou non
    mais j'aimerai aussi pourvoir aller directement à un noeud en utilisant du code, et je n'arrive pas à programmer cela
    j'ai recherché comment faire sur le net mais les exemples fournis sont tellement complexes que je m'en sort pas
    cela se passe dans la méthode : private void ExpandFolder(TreeView treeView1, string SelectedPath)
    Pouvez-vous m'aider ? Merci d'avance

    Je mets ci-dessous un exemple simplifié :

    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
    Xaml :
    
    <Window x:Class="WpfApplication1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="400" Width="500">
        
        <Grid>
            <TreeView Height="296" HorizontalAlignment="Left" Margin="12,12,0,0" Name="treeView1" VerticalAlignment="Top" Width="341"
                      SelectedItemChanged="treeView1_SelectedItemChanged">
                <TreeView.Resources>
                    <Style TargetType="{x:Type TreeViewItem}">
                        <Setter Property="HeaderTemplate">
                            <Setter.Value>
                                <DataTemplate>
                                    <StackPanel Orientation="Horizontal">
                                        <TextBlock Text="{Binding}" Margin="5,0" />
                                    </StackPanel>
                                </DataTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </TreeView.Resources>            
            </TreeView>
            <Button Content="Afficher" Height="23" HorizontalAlignment="Left" Margin="368,12,0,0" Name="button1" VerticalAlignment="Top" Width="98" Click="button1_Click" />
            <Button Content="Aller au noeud" Height="23" HorizontalAlignment="Left" Margin="368,64,0,0" Name="button2" VerticalAlignment="Top" Width="98" Click="button2_Click" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="12,326,0,0" Name="textBox1" VerticalAlignment="Top" Width="454" />
        </Grid>
    </Window>
    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
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    Code :
    
        public partial class MainWindow : Window
        {
            private object dummyNode = null;
    
            public MainWindow()
            {
                InitializeComponent();
            }
    
            private void treeView1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
            {
                string SelectedImagePath = "";
    
                TreeView tree = (TreeView)sender;
                TreeViewItem temp = ((TreeViewItem)tree.SelectedItem);
    
                if (temp == null)
                    return;
    
                string temp1 = "";
                string temp2 = "";
    
                while (true)
                {
                    temp1 = temp.Header.ToString();
    
                    if (temp1.Contains(@"\"))
                    {
                        temp2 = "";
                    }
    
                    SelectedImagePath = temp1 + temp2 + SelectedImagePath;
    
                    if (temp.Parent.GetType().Equals(typeof(TreeView)))
                    {
                        break;
                    }
    
                    temp = ((TreeViewItem)temp.Parent);
                    temp2 = @"\";
                }
    
                textBox1.Text = SelectedImagePath;
            }
    
            private void button1_Click(object sender, RoutedEventArgs e)
            {
                treeView1.Items.Clear();
    
                foreach (string s in Directory.GetLogicalDrives())
                {
                    TreeViewItem item = new TreeViewItem();
    
                    item.Header = s;
                    item.Tag = s;
                    item.FontWeight = FontWeights.Normal;
                    item.Items.Add(dummyNode);
                    item.Expanded += new RoutedEventHandler(folder_Expanded);
                    treeView1.Items.Add(item);
                }
            }
    
            private void button2_Click(object sender, RoutedEventArgs e)
            {
                if (textBox1.Text != "")
                    ExpandFolder(treeView1, textBox1.Text);
            }
    
            void folder_Expanded(object sender, RoutedEventArgs e)
            {
                TreeViewItem item = (TreeViewItem)sender;
    
                if (item.Items.Count == 1 && item.Items[0] == dummyNode)
                {
                    item.Items.Clear();
                    try
                    {
                        foreach (string s in Directory.GetDirectories(item.Tag.ToString()))
                        {
                            TreeViewItem subitem = new TreeViewItem();
                            subitem.Header = s.Substring(s.LastIndexOf("\\") + 1);
                            subitem.Tag = s;
                            subitem.FontWeight = FontWeights.Normal;
                            subitem.Items.Add(dummyNode);
                            subitem.Expanded += new RoutedEventHandler(folder_Expanded);
                            item.Items.Add(subitem);
                        }
                    }
    
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
    
            private void ExpandFolder(TreeView treeView1, string SelectedPath)
            {
                Console.WriteLine(SelectedPath);
    
                // ???
            }
        }

  2. #2
    Expert confirmé
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2009
    Messages
    2 025
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Novembre 2009
    Messages : 2 025
    Points : 5 462
    Points
    5 462
    Par défaut
    J'imagine que tu vas devoir parcourir les items de ton treeview a la recherche de ton path.
    Je ne connais pas le treeview mais je pense qu'il y a moyen de travailler sur une collection (donc ici l'ensemble des path) plutôt que sur le treeview directement.

  3. #3
    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

    Tu peux afficher uniquement les TreeViewItems des Lecteurs au chargement du Form...
    Ensuite l'affichage des TreeViewItem des Dossiers ne se fait que si le TreeViewItem du Répertoire est mis à "IsExpanded=true" ,ceci pour accélérer l'affichage (cas des "gros disques" !!!)...
    Ensuite pour la recherche d'un TreeViewItem, il faut un Method de recherche "recursif",car le TreeView possède une arborescence (structure en arbre) d'enfants .
    Le Method de Recherche utilise le ItemsControl.ItemContainerGenerator.ContainerFromItem (TreeViewItem est un ItemsControl)...
    Ensuite le TreeViewItem selectionné doit avoir sa prop "IsExpanded = true", sinon le ContainerFromItem n'est pas disponible c.à.d qu'il est généré uniquement pour des éléments affichés....

    code xaml du Form :
    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
     
     
    <Window x:Class="WpfTreeFindNode.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
            <TreeView Height="296" HorizontalAlignment="Left" Margin="12,12,0,0" 
                      Name="treeView1" VerticalAlignment="Top" Width="341"
                      SelectedItemChanged="treeView1_SelectedItemChanged">
                <TreeView.Resources>
                    <Style TargetType="{x:Type TreeViewItem}">
                        <Setter Property="HeaderTemplate">
                            <Setter.Value>
                                <DataTemplate>
                                    <StackPanel Orientation="Horizontal">
                                        <TextBlock Text="{Binding}" Margin="5,0" />
                                    </StackPanel>
                                </DataTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </TreeView.Resources>
            </TreeView>
            <Button Content="Afficher" Height="23" HorizontalAlignment="Left" Margin="368,12,0,0" Name="button1" VerticalAlignment="Top" Width="98" Click="button1_Click" />
            <Button Content="Aller au noeud" Height="23" HorizontalAlignment="Left" Margin="368,64,0,0" Name="button2" VerticalAlignment="Top" Width="98" Click="button2_Click" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="12,326,0,0" Name="textBox1" VerticalAlignment="Top" Width="454" />
        </Grid>
     
    </Window>
    code behind .cs du form:

    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
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
     
     
    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.Shapes;
    using System.IO;
    using System.Windows.Controls.Primitives;
     
    namespace WpfTreeFindNode
    {
        /// <summary>
        /// Logique d'interaction pour Window1.xaml
        /// </summary>
        public partial class Window1 : Window
        {
     
            public Window1()
            {
                InitializeComponent();
     
           }
     
            private void Window_Loaded(object sender, RoutedEventArgs e)
            {
                foreach (DriveInfo drive in DriveInfo.GetDrives())
                {
                    TreeViewItem item = new TreeViewItem();
                    item.Tag = drive;
                    item.Header = drive.ToString();
                    item.Items.Add("*");
                    treeFileSystem.Items.Add(item);
                }
     
            }
     
            private void item_Expanded(object sender, RoutedEventArgs e)
            {
                TreeViewItem item = e.OriginalSource as TreeViewItem;
                item.Items.Clear();
                DirectoryInfo dir ;
                if (item.Tag.GetType() == typeof(DriveInfo))
                {
     
                    DriveInfo drive = item.Tag as DriveInfo;
                    dir = drive.RootDirectory;
                }
                else
                {
                    dir = item.Tag as DirectoryInfo;
     
                }
                try
                {
                    foreach (DirectoryInfo  subdir  in dir.GetDirectories())
                    {
                        TreeViewItem  newItem = new TreeViewItem();
                        newItem.Tag = subdir;
                        newItem.Header = subdir.ToString();
                        newItem.Items.Add("*");
                        item.Items.Add(newItem);
     
                    }
     
     
                }
                catch (FileNotFoundException ex)
                {
     
                    throw new Exception  (ex.FileName +ex.Message );
                }
     
            }
            TreeViewItem itemSelected = null;
            private void treeFileSystem_Selected(object sender, RoutedEventArgs e)
            {
                itemSelected = e.OriginalSource as TreeViewItem;
                textBox1.Text = itemSelected.Tag.ToString();
            }
     
     
     
            private void btnToNode_Click(object sender, RoutedEventArgs e)
            {
                if (itemSelected == null) return;
                if (txtSearch.Text == null) return;
     
                itemSelected.IsExpanded = true; //nota-bene
     
               Search(itemSelected, txtSearch.Text);
     
            }
     
            private void  Search(TreeViewItem tvi, string name)
            {
     
                foreach (object obj in tvi.Items)
                {
     
                    TreeViewItem item = (TreeViewItem)tvi.ItemContainerGenerator.ContainerFromItem(obj);
                    if (item == null) continue;
                    if (item.Header.ToString().ToLower() == name.ToLower())
                    {
     
                        item.Background = Brushes.Red;
     
                        item.IsExpanded = true;
     
                    }
     
                    if (item.Items.Count > 0)
     
                        this.Search(item,name );
     
                }
     
            }
     
     
        }
    }
    bon code......

  4. #4
    Membre à l'essai
    Homme Profil pro
    Consultant informatique
    Inscrit en
    Septembre 2011
    Messages
    10
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Consultant informatique
    Secteur : Finance

    Informations forums :
    Inscription : Septembre 2011
    Messages : 10
    Points : 14
    Points
    14
    Par défaut
    Bonjour,

    Je suis désolé, mais la solution que tu m'as fournis ne fonctionne pas et je ne connais pas suffisemment le TreeView pour arriver à boucler dans l'arborescence en utilisant le ItemsControl.ItemContainerGenerator.ContainerFromItem
    Je ne connais en fait pas du tout le TreeView ! en effet, c'est la 1ère fois que je tente de l'utiliser.

    en attendant, je continue mes recherches mais sans grand succès.
    merci quand-même d'avoir voulu m'aider.

Discussions similaires

  1. comment ouvrir une fenetre qui donne l'arborescence du disque dur ?
    Par blueLight dans le forum Interfaces Graphiques en Java
    Réponses: 7
    Dernier message: 01/10/2009, 23h26
  2. Élément SELECT et méthode click() (comment ouvrir une dropdown-list)
    Par Hibou57 dans le forum Général JavaScript
    Réponses: 5
    Dernier message: 30/07/2007, 09h38
  3. Réponses: 27
    Dernier message: 03/02/2003, 12h27
  4. TTreeView -> Comment ouvrir une unité ?
    Par DaLove dans le forum C++Builder
    Réponses: 2
    Dernier message: 08/12/2002, 11h30
  5. Réponses: 1
    Dernier message: 31/10/2002, 11h55

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