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 :

TreeView Multi Colonnes WPF 4 [Débutant(e)]


Sujet :

Windows Presentation Foundation

  1. #1
    Membre habitué
    Profil pro
    Inscrit en
    Juillet 2011
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2011
    Messages : 13
    Par défaut TreeView Multi Colonnes WPF 4
    Bonjour tout le monde,

    Je me permets de venir vous déranger car j'ai un problème dont je n'arrive pas à trouver la solution.
    J'ai récupéré un sample me permettant de faire un treeview multicolonne.
    Le problème est que j'aimerais binder une ObservableCollection mais que je n'y arrive pas :/
    Je suis un débutant et je galère vraiment....

    Donc en gros j'ai un fichier de ressources Generic.xaml avec :
    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
    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
    130
     
    <ResourceDictionary
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1">
     
        <!--Converter for Indentation of items-->
        <local:TreeListViewConverter x:Key="TreeListViewConverter"/>
     
        <!--Control Template for TreeViewItem's.-->
        <ControlTemplate TargetType="TreeViewItem" x:Key="TreeListViewItem">
            <!--Grid containing the current information and the subnodes.-->
            <StackPanel>
                <!--Border wrapping the content presenter.-->
                <Border x:Name="Border">
                    <!--GridViewRowPrsenter containing the current information.-->
                    <GridViewRowPresenter Content="{TemplateBinding Header}"
                        Columns="{Binding Columns, 
                        RelativeSource={RelativeSource Mode=FindAncestor, 
                        AncestorType=local:TreeListView}}"/>
                </Border>
                <!--ItemsPresenter containing the subnodes-->
                <ItemsPresenter x:Name="ItemsPresenter" Visibility="Collapsed"/>
            </StackPanel>
            <ControlTemplate.Triggers>
                <!--Trigger used to show the sub items-->
                <Trigger Property="IsExpanded" Value="True">
                    <Setter TargetName="ItemsPresenter" Property="Visibility" Value="Visible"/>
                </Trigger>
                <!--Trigger used to change the color based on selection-->
                <Trigger Property="IsSelected" Value="true">
                    <!--Change the background color-->
                    <Setter TargetName="Border" Property="Background"
                        Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                    <!--Change the foreground color-->
                    <Setter Property="Foreground" 
                        Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
                </Trigger>
                <!--Trigger used to change the color based on selection-->
                <MultiTrigger>
                    <MultiTrigger.Conditions>
                        <Condition Property="IsSelected" Value="true"/>
                        <Condition Property="IsSelectionActive" Value="false"/>
                    </MultiTrigger.Conditions>
                    <!--Change the background color-->
                    <Setter TargetName="Border" Property="Background"
                        Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
                    <!--Change the foreground color-->
                    <Setter Property="Foreground" 
                        Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
                </MultiTrigger>
                <!--Trigger used to change the color based on the status of the item-->
                <Trigger Property="IsEnabled" Value="false">
                    <!--Change the foreground color-->
                    <Setter Property="Foreground" 
                        Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
     
        <!--Control Template for TreeListViewExpander's.-->
        <ControlTemplate TargetType="{x:Type local:TreeListViewExpander}" x:Key="TreeListViewExpander">
            <StackPanel Orientation="Horizontal" x:Name="ContainerElement">
                <!--Use a FrameworkElement to indent the button-->
                <FrameworkElement Width="{Binding RelativeSource={x:Static RelativeSource.Self}, 
                    Converter={StaticResource TreeListViewConverter}}"/>
                <!--Use a standard toggle button-->
                <ToggleButton IsChecked="{Binding IsExpanded, RelativeSource={RelativeSource Mode=FindAncestor,
                    AncestorType=TreeViewItem}}" Width="9" Height="9" VerticalAlignment="Center" Margin="1"/>
            </StackPanel>
            <ControlTemplate.Triggers>
                <!--Trigger used to show/hide the expand button-->
                <DataTrigger Binding="{Binding HasItems, RelativeSource={RelativeSource Mode=FindAncestor,
                    AncestorType=TreeViewItem}}" Value="False">
                    <Setter TargetName="ContainerElement" Property="Visibility" Value="Hidden"/>
                </DataTrigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
     
        <!--Apply this style to all controls of type 'TreeListView'.-->
        <Style TargetType="{x:Type local:TreeListView}">
            <!--Set the control template.-->
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type local:TreeListView}">
                        <ControlTemplate.Resources>
                            <!--Apply this style to all 'TreeViewItem's.-->
                            <Style TargetType="TreeViewItem">
                                <Setter Property="Template" Value="{StaticResource TreeListViewItem}"/>
                            </Style>
                            <!--Apply this style to all 'TreeListViewExpander's.-->
                            <Style TargetType="local:TreeListViewExpander">
                                <Setter Property="Template" Value="{StaticResource TreeListViewExpander}"/>
                            </Style>
                        </ControlTemplate.Resources>
                        <!--Create a standard border around the 'TreeListView'.-->
                        <Border Background="{TemplateBinding Background}"
                                BorderBrush="{TemplateBinding BorderBrush}"
                                BorderThickness="{TemplateBinding BorderThickness}">
                            <!--ScrollViewer providing horizontal scrolling functionality 
                            for both, content and headers.-->
                            <ScrollViewer HorizontalScrollBarVisibility="Auto"
                                          VerticalScrollBarVisibility="Disabled">
                                <!--Grid containing the header row and all the content rows.-->
                                <Grid>
                                    <Grid.RowDefinitions>
                                        <!--The header row.-->
                                        <RowDefinition Height="Auto"/>
                                        <!--The content row.-->
                                        <RowDefinition Height="*"/>
                                    </Grid.RowDefinitions>
                                    <!--The header row.-->
                                    <GridViewHeaderRowPresenter Columns="{TemplateBinding Columns}"
                                        AllowsColumnReorder="{TemplateBinding AllowsColumnReorder}"/>
                                    <!--ScrollViewer providing vertical scrolling
                                    functionality for the content.-->
                                    <ScrollViewer HorizontalScrollBarVisibility="Disabled"
                                                  VerticalScrollBarVisibility="Auto"
                                                  Grid.Row="1">
                                        <!--ItemsPresenter containg the content.-->
                                        <ItemsPresenter/>
                                    </ScrollViewer>
                                </Grid>
                            </ScrollViewer>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ResourceDictionary>

    Une Classe TreeListView.cs avec :
    Code C# : 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
     
    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;
    using System.Windows.Controls.Primitives;
     
    namespace WpfApplication1
    {
        /// <summary>
        /// Represents a control that displays hierarchical data in a tree structure
        /// that has items that can expand and collapse.
        /// </summary>
        public class TreeListView : TreeView
        {
            static TreeListView()
            {
                //Override the default style and the default control template
                DefaultStyleKeyProperty.OverrideMetadata(typeof(TreeListView), new FrameworkPropertyMetadata(typeof(TreeListView)));
            }
     
            /// <summary>
            /// Initialize a new instance of TreeListView.
            /// </summary>
            public TreeListView()
            {
                Columns = new GridViewColumnCollection();
            }
     
            #region Properties
            /// <summary>
            /// Gets or sets the collection of System.Windows.Controls.GridViewColumn 
            /// objects that is defined for this TreeListView.
            /// </summary>
            public GridViewColumnCollection Columns
            {
                get { return (GridViewColumnCollection)GetValue(ColumnsProperty); }
                set { SetValue(ColumnsProperty, value); }
            }
     
            /// <summary>
            /// Gets or sets whether columns in a TreeListView can be
            /// reordered by a drag-and-drop operation. This is a dependency property.
            /// </summary>
            public bool AllowsColumnReorder
            {
                get { return (bool)GetValue(AllowsColumnReorderProperty); }
                set { SetValue(AllowsColumnReorderProperty, value); }
            }
            #endregion
     
            #region Static Dependency Properties
            // Using a DependencyProperty as the backing store for AllowsColumnReorder.  This enables animation, styling, binding, etc...
            public static readonly DependencyProperty AllowsColumnReorderProperty =
                DependencyProperty.Register("AllowsColumnReorder", typeof(bool), typeof(TreeListView), new UIPropertyMetadata(null));
     
            // Using a DependencyProperty as the backing store for Columns.  This enables animation, styling, binding, etc...
            public static readonly DependencyProperty ColumnsProperty =
                DependencyProperty.Register("Columns", typeof(GridViewColumnCollection),
                typeof(TreeListView),
                new UIPropertyMetadata(null));
            #endregion
        }
     
        /// <summary>
        /// Represents a control that can switch states in order to expand a node of a TreeListView.
        /// </summary>
        public class TreeListViewExpander : ToggleButton { }
     
        /// <summary>
        /// Represents a convert that can calculate the indentation of any element in a class derived from TreeView.
        /// </summary>
        public class TreeListViewConverter : IValueConverter
        {
            public const double Indentation = 10;
     
            #region IValueConverter Members
     
            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                //If the value is null, don't return anything
                if (value == null) return null;
                //Convert the item to a double
                if (targetType == typeof(double) && typeof(DependencyObject).IsAssignableFrom(value.GetType()))
                {
                    //Cast the item as a DependencyObject
                    DependencyObject Element = value as DependencyObject;
                    //Create a level counter with value set to -1
                    int Level = -1;
                    //Move up the visual tree and count the number of TreeViewItem's.
                    for (; Element != null; Element = VisualTreeHelper.GetParent(Element))
                        //Check whether the current elemeent is a TreeViewItem
                        if (typeof(TreeViewItem).IsAssignableFrom(Element.GetType()))
                            //Increase the level counter
                            Level++;
                    //Return the indentation as a double
                    return Indentation * Level;
                }
                //Type conversion is not supported
                throw new NotSupportedException(
                    string.Format("Cannot convert from <{0}> to <{1}> using <TreeListViewConverter>.",
                    value.GetType(), targetType));
            }
     
            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                throw new NotSupportedException("This method is not supported.");
            }
     
            #endregion
        }
     
    }

    et enfin ma fenêtre TestTree.xaml ou je n'arrive pas à binder ma collection.... :
    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
    53
    54
    55
    56
    57
    58
    59
    60
    61
     
    <Window x:Class="WpfApplication1.TestTree"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfApplication1"
            Title="TestTree" Height="402" Width="878">
        <local:TreeListView AllowsColumnReorder="True">
            <!--Create an item template to specify the ItemsSource-->
            <local:TreeListView.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Children}" />
            </local:TreeListView.ItemTemplate>
            <local:TreeListView.Columns>
                <!--Create the first column containing the expand button and the type name.-->
                <GridViewColumn Header="Name" Width="400">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <!--The Expander Button (can be used in any column (typically the first one))-->
                                <local:TreeListViewExpander/>
                                <!--Display the name of the DataElement-->
                                <TextBlock Text="{Binding}"/>
                            </StackPanel>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <!--Create a second column containing the number of children.-->
                <GridViewColumn Header="Children" Width="100">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <!--Display the size of the DataElement-->
                            <TextBlock Text="{Binding Children.Count}" HorizontalAlignment="Right"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <!--Create a third column containing the brush of the material.-->
                <GridViewColumn Header="Brush" Width="100">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <!--Border showing the actual color-->
                                <Border Background="{Binding Brush}" CornerRadius="2"
                                        Width="16" Height="16"
                                        BorderThickness="1" BorderBrush="DarkGray"/>
                                <!--Display the brush-->
                                <TextBlock Text="{Binding Brush}"/>
                            </StackPanel>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </local:TreeListView.Columns>
            <!--Create some sample data-->
            <MaterialGroup>
                <MaterialGroup>
                    <DiffuseMaterial Brush="Blue"/>
                    <DiffuseMaterial Brush="Red"/>
                    <SpecularMaterial Brush="Orange"/>
                </MaterialGroup>
                <EmissiveMaterial Brush="AliceBlue"/>
            </MaterialGroup>
        </local:TreeListView>
    </Window>

    Je suis vraiment désolé pour le gros "paté" mais je craque la

  2. #2
    Membre Expert
    Avatar de GuruuMeditation
    Homme Profil pro
    .Net Architect
    Inscrit en
    Octobre 2010
    Messages
    1 705
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 50
    Localisation : Belgique

    Informations professionnelles :
    Activité : .Net Architect
    Secteur : Conseil

    Informations forums :
    Inscription : Octobre 2010
    Messages : 1 705
    Par défaut
    Faut enlever le <MaterialGroup> du treeview, et binder vers ta collection. Exemple :
    Code c# : 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
     
     public partial class MainWindow
        {
            public ObservableCollection<Data> TreeViewSource { get; set; }
     
            public MainWindow()
            {
     
                TreeViewSource = new ObservableCollection<Data> { new Data { Nom = "Niveau 1", Brush = new SolidColorBrush(Colors.Blue), Children = new ObservableCollection<Data> { new Data { Nom = "Niveau 2 (1)", Brush = new SolidColorBrush(Colors.White) }, new Data { Nom = "Niveau 2 (1)", Brush = new SolidColorBrush(Colors.Red) } } } };
     
                this.DataContext = this;
     
                InitializeComponent();
            }
        }
     
     
        public class Data
        {
            public string Nom { get; set; }
     
            public SolidColorBrush Brush { get; set; }
     
            public ObservableCollection<Data> Children { get; set; }
        }

    Et le XAML (J'ai enlevé les MaterialGroup et mis le ItemSource pour le binding ):
    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
    53
    54
    55
    56
     
    <local:TreeListView AllowsColumnReorder="True"
                            ItemsSource="{Binding TreeViewSource}">
            <!--Create an item template to specify the ItemsSource-->
            <local:TreeListView.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Children}" />
            </local:TreeListView.ItemTemplate>
            <local:TreeListView.Columns>
                <!--Create the first column containing the expand button and the type name.-->
                <GridViewColumn Header="Name" Width="200">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <!--The Expander Button (can be used in any column (typically the first one))-->
                                <local:TreeListViewExpander/>
                                <!--Display the name of the DataElement-->
                                <TextBlock Text="{Binding}"/>
                            </StackPanel>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <!--Create a second column containing the number of children.-->
                <GridViewColumn Header="Children" Width="100">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>                        
                            <!--Display the size of the DataElement-->
                            <TextBlock Text="{Binding Children.Count}" HorizontalAlignment="Right"/>                        
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <!--Create a third column containing the brush of the material.-->
                <GridViewColumn Header="Brush" Width="100">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <!--Border showing the actual color-->
                                <Border Background="{Binding Brush}" CornerRadius="2"
                                        Width="16" Height="16"
                                        BorderThickness="1" BorderBrush="DarkGray"/>
                                <!--Display the brush-->
                                <TextBlock Text="{Binding Brush}"/>
                            </StackPanel>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </local:TreeListView.Columns>
            <!--Create some sample data-->
            <!--<MaterialGroup>
                <MaterialGroup>
                    <DiffuseMaterial Brush="Blue"/>
                    <DiffuseMaterial Brush="Red"/>
                    <SpecularMaterial Brush="Orange"/>
                </MaterialGroup>
                <EmissiveMaterial Brush="AliceBlue"/>
            </MaterialGroup>-->
        </local:TreeListView>

  3. #3
    Membre habitué
    Profil pro
    Inscrit en
    Juillet 2011
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2011
    Messages : 13
    Par défaut
    J'ai essayé d'utiliser un treeview sans multi colonnes tout simple via ce code :

    Code xaml : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
    <Window x:Class="WpfApplication1.Tree"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="Tree" Height="481" Width="760">
        <TreeView ItemsSource="{Binding ARAMCollection}" Height="369" Width="676" >
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding PlayerName}">
                    <TextBlock FontWeight="Bold" Text="{Binding}" />            
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>
    </Window>

    Et malheureusement je n'obtiens rien :/ ma fenêtre est vide.
    Ma classe fonctionne car je l'utilise avec une ListView et je n'ai aucun problème d'où mon incompréhension :/

  4. #4
    Membre Expert
    Avatar de GuruuMeditation
    Homme Profil pro
    .Net Architect
    Inscrit en
    Octobre 2010
    Messages
    1 705
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 50
    Localisation : Belgique

    Informations professionnelles :
    Activité : .Net Architect
    Secteur : Conseil

    Informations forums :
    Inscription : Octobre 2010
    Messages : 1 705
    Par défaut
    Le datacontext est bien mis? PlayerName est bien une liste?

  5. #5
    Membre habitué
    Profil pro
    Inscrit en
    Juillet 2011
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2011
    Messages : 13
    Par défaut
    Oui le DataContext est mis.
    PlayerName correspond au champs "Name" de votre exemple dans la Class Data

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
        public partial class Tree : Window
        {
            public Tree()
            {
                UTILS.OnlineCollection = UTILS.ARAMCollection;
                this.DataContext = this;
                InitializeComponent();
             }
        }
    La classe UTILS contient la déclaration des Collection OnlineCollection et ARAMCollection. ARAMCollection est remplie dans cette classe UTILS


    Ma classe Player se trouvant dans un fichier séparé :
    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
     
    public class Player
    {
        private string _PlayerName;
        private string _ScorePlayer;
     
        public string PlayerName
        {
            get { return _PlayerName; }
            set { _PlayerName = value; }
        }
     
        public string ScorePlayer
        {
            get { return _ScorePlayer; }
            set { _ScorePlayer = value; }
        }
     
        public Ban(string PN, string SP)
        {
            _PlayerName = PN;
            _ScorePlayer = SP;
        }
    }
    Ce que je souhaite dans mon treeview :
    Colonne1_______Colonne2_______________Colonne3
    PlayerName1
    -------------- ScorePlayer1 ------- Type Collection(ARAM ou Online)
    -------------- ScorePlayer1 ------- Type Collection(ARAM ou Online)
    -------------- ScorePlayer1 ------- Type Collection(ARAM ou Online)
    PlayerName2
    -------------- ScorePlayer2 ------- Type Collection(ARAM ou Online)
    -------------- ScorePlayer2 ------- Type Collection(ARAM ou Online)
    -------------- ScorePlayer2 ------- Type Collection(ARAM ou Online)
    J'éspère que c'est peu plus claire Je pensais pas que je galérerais autant étant donné que j'ai pas eu de prob pour exploiter mes collections avant une listview :/

  6. #6
    Membre habitué
    Profil pro
    Inscrit en
    Juillet 2011
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2011
    Messages : 13
    Par défaut
    Bon j'obtiens enfin quelque chose mais pas vraiment ce que je veux
    En fait j'obtiens :
    - WpfApplication1.Player
    P
    L
    A
    Y
    E
    R
    N
    A
    M
    E
    1
    - WpfApplication1.Player
    P
    L
    A
    Y
    E
    R
    N
    A
    M
    E
    2
    - WpfApplication1.Player.....

    Donc il m'écrit ma Class alors que je veux le champ PlayerName
    et le champs PlayerName est écrit verticalement

  7. #7
    Membre Expert
    Avatar de GuruuMeditation
    Homme Profil pro
    .Net Architect
    Inscrit en
    Octobre 2010
    Messages
    1 705
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 50
    Localisation : Belgique

    Informations professionnelles :
    Activité : .Net Architect
    Secteur : Conseil

    Informations forums :
    Inscription : Octobre 2010
    Messages : 1 705
    Par défaut
    Pas sûr exactement de ce que tu veux dans la 3eme colonne. Si c'est juste une donnée "plate" (pas de collection), ce que tu cherches est peut-etre plutot une ListView groupée sur le nom du joueur.

    En attendant, voila quelque chose qui correspond à ce que tu cherches en TreeView. L'astuce est d'utiliser un DataTemplateSelector selon qu'on soit sur un type Player, ou un type string (pour le score):
    La structure Player
    Code C# : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
        public class Player
        {
            public string PlayerName { get; set; }
     
            public ObservableCollection<string> Score { get; set; }
        }
    Le DataTemplateSelector :
    Code C# : 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
     
      public class ScoreTemplateSelector : DataTemplateSelector
        {
            public override DataTemplate SelectTemplate(object item, DependencyObject container)
            {
                var element = container as FrameworkElement;
     
                if ((element == null) || (item == null))
                    return null;
     
                if (item is Player)
                {
                    return element.FindResource("EmptyTemplate") as DataTemplate;
                }
                if (item is string)
                {
                    return element.FindResource("ScoreTemplate") as DataTemplate;
                }
     
                return null;
            }
        }

    Et le 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
    53
     
        <local:TreeListView AllowsColumnReorder="True"
                            ItemsSource="{Binding TreeViewSource}">
            <local:TreeListView.Resources>
                <DataTemplate x:Key="ScoreTemplate">
                    <!--Display the size of the DataElement-->
                    <TextBlock Text="{Binding}"
                               HorizontalAlignment="Right" />
                </DataTemplate>
                <DataTemplate x:Key="EmptyTemplate">
                </DataTemplate>
                <local:ScoreTemplateSelector x:Key="ScoreTemplateSelector" />
            </local:TreeListView.Resources>
            <!--Create an item template to specify the ItemsSource-->
            <local:TreeListView.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Score}">
                </HierarchicalDataTemplate>
     
            </local:TreeListView.ItemTemplate>
            <local:TreeListView.Columns>
                <!--Create the first column containing the expand button and the type name.-->
                <GridViewColumn Header="PlayerName" Width="200" >
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <!--The Expander Button (can be used in any column (typically the first one))-->
                                <local:TreeListViewExpander/>
                                <!--Display the name of the DataElement-->
                                <TextBlock Text="{Binding PlayerName}" />
                            </StackPanel>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <!--Create a second column containing the number of children.-->
                <GridViewColumn Header="Score"
                                Width="100"
                                CellTemplateSelector="{StaticResource ScoreTemplateSelector}">
     
                </GridViewColumn>
                <!--Create a third column containing the brush of the material.-->
                <GridViewColumn Header="Class" Width="100">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <!--Border showing the actual color-->
                                <!--Display the brush-->
                                <!--<TextBlock Text="{Binding}"/>-->
                            </StackPanel>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </local:TreeListView.Columns>
        </local:TreeListView>

    Je n'ai rien mis en 3ème colonne, car comme je l'ai dit je ne suis pas sûr de ce qu'il faut mettre.

  8. #8
    Membre habitué
    Profil pro
    Inscrit en
    Juillet 2011
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2011
    Messages : 13
    Par défaut
    Oui ce sont des données plates, en fait je voulais un TreeView question d'esthétisme concernant la hiérarchie.
    J'ai juste 2 collections avec pour chacune d'elles 3 champs : PlayerName(string), ScorePlayer(String), CollectionType(String)

  9. #9
    Membre habitué
    Profil pro
    Inscrit en
    Juillet 2011
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2011
    Messages : 13
    Par défaut
    J'ai testé avec un DataTemplateSelector et cela fonctionne enfin
    Malheureusement, si j'utilise le code suivant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
    public ObservableCollection<TreeCollection> OnlineCollection = new ObservableCollection<TreeCollection>();
     
    public MainWin()
    {
     
    OnlineCollection.Add(new TreeCollection{PlayerName = "Infra",Children = new ObservableCollection<TreeCollection> { new TreeCollection{ PlayerName = "Player1", BanReason = "Leaver", ListTyp = "ARAM"},
    new TreeCollection { PlayerName = "Player2", BanReason = "AFK", ListTyp = "ARAM"}, new TreeCollection { PlayerName = "Player3", BanReason = "Selection Leave", ListTyp = "ARAM"}}});
    this.DataContext = this;            
    InitializeComponent();
     
    }
    au lieu de :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
    public ObservableCollection<TreeCollection> OnlineCollection { get; set; }
     
    public MainWin()
    {
     
    OnlineCollection = new ObservableCollection<TreeCollection> { new TreeCollection { PlayerName = "Infra", Children = new ObservableCollection<TreeCollection> { new TreeCollection{ PlayerName = "Player1", BanReason = "Leaver", ListTyp = "ARAM"},
    new TreeCollection { PlayerName = "Player2", BanReason = "AFK", ListTyp = "ARAM"}, new TreeCollection { PlayerName = "Player3", BanReason = "Selection Leave", ListTyp = "ARAM" } } } };
    this.DataContext = this;            
    InitializeComponent();
     
    }
    mon treeview ne fonctionne plus :/

  10. #10
    Membre Expert
    Avatar de GuruuMeditation
    Homme Profil pro
    .Net Architect
    Inscrit en
    Octobre 2010
    Messages
    1 705
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 50
    Localisation : Belgique

    Informations professionnelles :
    Activité : .Net Architect
    Secteur : Conseil

    Informations forums :
    Inscription : Octobre 2010
    Messages : 1 705
    Par défaut
    C'est parce que dans l'exemple qui ne fonctionne pas, OnlineCollection n'est pas une propriété (il n'a pas de "get;set;") mais un champ. Et pour le binding, c'est pas bon.

  11. #11
    Membre habitué
    Profil pro
    Inscrit en
    Juillet 2011
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2011
    Messages : 13
    Par défaut
    Oui oui je sais mais bon j'ai essayé d'ajouter plusieurs données via la propriété et il ne garde que la dernière

  12. #12
    Membre habitué
    Profil pro
    Inscrit en
    Juillet 2011
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2011
    Messages : 13
    Par défaut
    J'ai bien essayé la méthode traditionnelle d'ajout de noeud mais sans succés. Après, j'ai peut être merdé quelque part ^^

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    TreeViewItem newChild = new TreeViewItem();
    OnlineCollection = new ObservableCollection<TreeCollection> { new TreeCollection { PlayerName = "Infra", Children = new ObservableCollection<TreeCollection> { new TreeCollection{ PlayerName = "Player1", BanReason = "Leaver", ListTyp = "ARAM"},
    new TreeCollection { PlayerName = "Player2", BanReason = "AFK", ListTyp = "ARAM"}, new TreeCollection { PlayerName = "Player3", BanReason = "Selection Leave", ListTyp = "ARAM" } } } };
    newChild.Header(OnlineCollection);
    TreeView1.Items.add(newChild);

  13. #13
    Membre Expert
    Avatar de GuruuMeditation
    Homme Profil pro
    .Net Architect
    Inscrit en
    Octobre 2010
    Messages
    1 705
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 50
    Localisation : Belgique

    Informations professionnelles :
    Activité : .Net Architect
    Secteur : Conseil

    Informations forums :
    Inscription : Octobre 2010
    Messages : 1 705
    Par défaut
    essaye avec :
    Code C# : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    newChild.ItemsSource = OnlineCollection;

  14. #14
    Membre habitué
    Profil pro
    Inscrit en
    Juillet 2011
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2011
    Messages : 13
    Par défaut
    Arghhh ca passe pas
    [System.NullReferenceException] = {"La référence d'objet n'est pas définie à une instance d'un objet."}
    sur le treeview.items.add

  15. #15
    Membre extrêmement actif
    Inscrit en
    Avril 2008
    Messages
    2 573
    Détails du profil
    Informations personnelles :
    Âge : 65

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 573
    Par défaut TreeView ou TreeListView multicolonne
    Bonjour mso54
    Dans la continuite de ce que recommende GuruuMeditation pour la structure de ta classe Player ,voici un code complete pour l'utilisation du Custom Control TreeViewList de la SDK MSDN fr (voir lien à la fin):
    le custom control MSDN que j'ai mis dans Application.Resources a ete modifie comme suit:
    1/La collection GridViewCollection designe par la cle "gvvcc" a ete modifie pour etre lie aux champs PlayerScore et LstType de la classe Player.

    2/le DataTemplate du modele cellule de la la 1ere colonne de la collection GridViewCollection designe par la cle "CellTemplate_Name a ete lie à la prop PlayerName de la classe Ligue.
    code xaml du custom control MSDN:
    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
    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
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
     
    <Application x:Class="WpfListePlayersCSharp.App"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfListePlayersCSharp"
        StartupUri="MainWinTreeListPlayers.xaml">
        <!--code xaml du custom control  TreeListView MSDN-->
        <Application.Resources>
     
            <Style x:Key="ExpandCollapseToggleStyle"
               TargetType="{x:Type ToggleButton}">
                <Setter
                    Property="Focusable"
                    Value="False"/>
                <Setter 
                    Property="Width"
                    Value="19"/>
                <Setter 
                    Property="Height"
                    Value="13"/>
                <Setter 
                    Property="Template">
                    <Setter.Value>
                        <ControlTemplate 
                            TargetType="{x:Type ToggleButton}">
                            <Border 
                                Width="19"
                                Height="13"
                                Background="Transparent">
                                <Border
                                    Width="9"
                                    Height="9"
                                    BorderThickness="1"
                                    BorderBrush="#FF7898B5"
                                    CornerRadius="1"
                                    SnapsToDevicePixels="true">
                                    <Border.Background>
                                        <LinearGradientBrush 
                                            StartPoint="0,0"
                                            EndPoint="1,1">
                                            <LinearGradientBrush.GradientStops>
                                                <GradientStop 
                                                    Color="White"
                                                    Offset=".2"/>
                                                <GradientStop 
                                                    Color="#FFC0B7A6"
                                                    Offset="1"/>
                                            </LinearGradientBrush.GradientStops>
                                        </LinearGradientBrush>
                                    </Border.Background>
                                    <Path 
                                        x:Name="ExpandPath"
                                        Margin="1,1,1,1"
                                        Fill="Black"
                                        Data="M 0 2 L 0 3 L 2 3 L 2 5 L 3 5 L 3 3 
                                        L 5 3 L 5 2 L 3 2 L 3 0 L 2 0 L 2 2 Z"/>
                                </Border>
                            </Border>
                            <ControlTemplate.Triggers>
                                <Trigger 
                                    Property="IsChecked"
                                   Value="True">
                                    <Setter 
                                        Property="Data"
                                        TargetName="ExpandPath"
                                        Value="M 0 2 L 0 3 L 5 3 L 5 2 Z"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
     
            <local:LevelToIndentConverter
                x:Key="LevelToIndentConverter"/>
     
            <!-- TextBlock  orginal du SDK sample binde sur Name du Type -->
            <!-- c.à.d "Classe Ligue" a ete binde sur PlayerName -->
            <!--<TextBlock 
                            Text="{Binding Name}"/>-->
            <DataTemplate 
                x:Key="CellTemplate_Name">
                <DockPanel>
                    <ToggleButton 
                        x:Name="Expander" 
                          Style="{StaticResource ExpandCollapseToggleStyle}" 
                          Margin="{Binding Level,
                                 Converter={StaticResource 
                                 LevelToIndentConverter},
                                 RelativeSource={RelativeSource 
                                                 AncestorType=
                                                 {x:Type local:TreeListViewItem}}}"
                          IsChecked="{Binding Path=IsExpanded,
                                     RelativeSource={RelativeSource 
                                                     AncestorType=
                                                     {x:Type local:TreeListViewItem}}}"
                          ClickMode="Press"/>
                    <TextBlock 
                        FontSize="14"
                        Foreground="DarkBlue"
                        Text="{Binding PlayerName}"/>
                </DockPanel>
                <DataTemplate.Triggers>
                    <DataTrigger 
                        Binding="{Binding Path=HasItems,
                        RelativeSource={RelativeSource 
                        AncestorType={x:Type local:TreeListViewItem}}}" 
                        Value="False">
                        <Setter 
                            TargetName="Expander"
                            Property="Visibility"
                            Value="Hidden"/>
                    </DataTrigger>
                </DataTemplate.Triggers>
            </DataTemplate>
     
            <!--le gvvcc orginal du SDK sample a ete modifie-->
            <!--les GridViewColumn originaux avait ete bindes sur-->  
            <!--des classes du .Net FrameWork choisies comme data exemple(bizarre!)-->  
            <!--Modifier pour l'adapter à la classe Player-->
            <!--<GridViewColumnCollection 
                x:Key="gvcc">
                <GridViewColumn 
                    Header="Name"  
                    CellTemplate="{StaticResource CellTemplate_Name}" />
                <GridViewColumn
                    Header="IsAbstract" 
                    DisplayMemberBinding="{Binding IsAbstract}" 
                    Width="60" />
                <GridViewColumn 
                    Header="Namespace" 
                    DisplayMemberBinding="{Binding Namespace}" />
            </GridViewColumnCollection>-->
            <!-- ic : gvvcc Modifie -->
            <GridViewColumnCollection  
                x:Key="gvcc"  >
                <GridViewColumn 
                    Header="Player Name" 
                    CellTemplate="{StaticResource CellTemplate_Name}" />
                <GridViewColumn
                    Header="Player Score" 
                    DisplayMemberBinding="{Binding ScorePlayer}" 
                    Width="60" />
                <GridViewColumn 
                    Header="Team Type" 
                    DisplayMemberBinding="{Binding ListTyp}"
                    Width="60" /> 
            </GridViewColumnCollection>
     
            <!-- ControlTemplate du TreeListViewItem: definit par un Style. -->
            <!-- GridViewRowPresenter :son Content definit le Header du TreeListViewItem -->
            <!-- Contenu des colonnes "data" : binde sur "gvcc" cite ci-dessus -->
     
            <Style 
                TargetType="{x:Type local:TreeListViewItem}">
                <Setter 
                    Property="Template">
                    <Setter.Value>
                        <ControlTemplate 
                            TargetType="{x:Type local:TreeListViewItem}">
                            <StackPanel>
                                <Border 
                                    Name="Bd"
                                    Background="{TemplateBinding Background}"
                                    BorderBrush="{TemplateBinding BorderBrush}"
                                    BorderThickness="{TemplateBinding BorderThickness}"
                                    Padding="{TemplateBinding Padding}" >
                                    <GridViewRowPresenter 
                                        x:Name="PART_Header" 
                                        Content="{TemplateBinding Header}" 
                                        Columns="{StaticResource gvcc}"/>  
                                </Border>
                                <ItemsPresenter 
                                    x:Name="ItemsHost"/> 
                            </StackPanel>
                            <ControlTemplate.Triggers>
                                <Trigger 
                                    Property="IsExpanded"
                                    Value="false">
                                    <Setter 
                                        TargetName="ItemsHost"
                                        Property="Visibility"
                                        Value="Collapsed"/>
                                </Trigger>
                                <MultiTrigger>
                                    <MultiTrigger.Conditions>
                                        <Condition 
                                            Property="HasHeader"
                                            Value="false"/>
                                        <Condition 
                                            Property="Width"
                                            Value="Auto"/>
                                    </MultiTrigger.Conditions>
                                    <Setter 
                                        TargetName="PART_Header"
                                        Property="MinWidth"
                                        Value="75"/>
                                </MultiTrigger>
                                <MultiTrigger>
                                    <MultiTrigger.Conditions>
                                        <Condition
                                            Property="HasHeader"
                                            Value="false"/>
                                        <Condition 
                                            Property="Height"
                                            Value="Auto"/>
                                    </MultiTrigger.Conditions>
                                    <Setter 
                                        TargetName="PART_Header"
                                        Property="MinHeight"
                                        Value="19"/>
                                </MultiTrigger>
                                <Trigger 
                                    Property="IsSelected"
                                    Value="true">
                                    <Setter 
                                        TargetName="Bd"
                                        Property="Background"
                                        Value="{DynamicResource 
                                              {x:Static SystemColors.HighlightBrushKey}}"/>
                                    <Setter 
                                        Property="Foreground"
                                        Value="{DynamicResource 
                                              {x:Static SystemColors.HighlightTextBrushKey}}"/>
                                </Trigger>
                                <MultiTrigger>
                                    <MultiTrigger.Conditions>
                                        <Condition 
                                            Property="IsSelected"
                                            Value="true"/>
                                        <Condition 
                                            Property="IsSelectionActive"
                                            Value="false"/>
                                    </MultiTrigger.Conditions>
                                    <Setter 
                                        TargetName="Bd"
                                        Property="Background"
                                        Value="{DynamicResource 
                                              {x:Static SystemColors.ControlBrushKey}}"/>
                                    <Setter 
                                        Property="Foreground"
                                        Value="{DynamicResource 
                                              {x:Static SystemColors.ControlTextBrushKey}}"/>
                                </MultiTrigger>
                                <Trigger 
                                    Property="IsEnabled"
                                    Value="false">
                                    <Setter 
                                        Property="Foreground"
                                        Value="{DynamicResource 
                                              {x:Static SystemColors.GrayTextBrushKey}}"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
     
            <!-- ControlTemplate du TreeListView: definit par un Style. -->
            <!-- Controle visuel definit :par un GridViewHeaderRowPresenter  -->
            <!-- Contenu des colonnes "Headers" : binde sur "gvcc" cite ci-dessus -->
            <Style 
                TargetType="{x:Type local:TreeListView}">
                <Setter 
                    Property="Template">
                    <Setter.Value>
                        <ControlTemplate 
                            TargetType="{x:Type local:TreeListView}">
                            <Border 
                                BorderBrush="{TemplateBinding BorderBrush}"
                                BorderThickness="{TemplateBinding BorderThickness}">
                                <DockPanel>
                                    <GridViewHeaderRowPresenter 
                                        Columns="{StaticResource gvcc}"
                                        DockPanel.Dock="Top"/>
                                    <ItemsPresenter/>
                                </DockPanel>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </Application.Resources>
    </Application>
    code behind du custom control MSDN:
    Code c# : 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
     
    //  Classe LevelToIndentConverter : SDK MSDN (voir lien MSDN)
    //  convertit le niveau(profondeur)d'un TreeViewItem 
    //  en marge d'affichage de type Thickness(car unite de Margin=Thickness)
    // 
     
    using System;
    using System.Windows.Controls;
    using System.Windows;
    using System.Windows.Data;
    using System.Globalization;
     
     
    namespace WpfListePlayersCSharp
    {
        /// <summary>
        /// Convert Level to left margin
        /// Pass a prarameter if you want a unit length other than 19.0.
        /// </summary>
        public class LevelToIndentConverter : IValueConverter
        {
            public object Convert(object o, Type type, object parameter, 
                                  CultureInfo culture)
            {
                return new Thickness((int)o * c_IndentSize, 0, 0, 0);
            }
     
            public object ConvertBack(object o, Type type, object parameter, 
                                      CultureInfo culture)
            {
                throw new NotSupportedException();
            }
     
            private const double c_IndentSize = 19.0;
        }
    }
     
    //  Classe du custom control TreeListView :un custom TreeView du SDK MSDN 
    //  create a custom view that resembles the GridView view mode 
    // 
     
    using System;
    using System.Windows.Controls;
    using System.Windows;
     
     
    namespace WpfListePlayersCSharp
    {
        public class TreeListView : TreeView
        {
            protected override DependencyObject 
                               GetContainerForItemOverride()
            {
                return new TreeListViewItem();
            }
     
            protected override bool 
                               IsItemItsOwnContainerOverride(object item)
            {
                return item is TreeListViewItem;
            }
        }
     
        public class TreeListViewItem : TreeViewItem
        {
            /// <summary>
            /// Item's hierarchy in the tree
            /// </summary>
            public int Level
            {
                get
                {
                    if (_level == -1)
                    {
                        TreeListViewItem parent = 
                            ItemsControl.ItemsControlFromItemContainer(this) 
                                as TreeListViewItem;
                        _level = (parent != null) ? parent.Level + 1 : 0;
                    }
                    return _level;
                }
            }
     
     
            protected override DependencyObject 
                               GetContainerForItemOverride()
            {
                return new TreeListViewItem();
            }
     
            protected override bool IsItemItsOwnContainerOverride(object item)
            {
                return item is TreeListViewItem;
            }
     
            private int _level = -1;
        }
     
    }
    code behind de la classe Player et Ligue,vu que tu veux 2 niveaux(2 TreeViewItem) il te faut 2 listes ....n'est ce pas? ) :
    Code c# : 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
     
    // Classe Player :un joueur
    //
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.ComponentModel;
    using System.Collections.ObjectModel;
    namespace WpfListePlayersCSharp
    {
        //Classe Player
        public class Player:INotifyPropertyChanged
        {
            public Player()
            {
            }
            public Player( string objScorePlayer, string objListTyp)
                :base()
            {
                _ScorePlayer=objScorePlayer ;
                _ListTyp=objListTyp;
            }
            private string _ScorePlayer;
            public string ScorePlayer
            {
                get { return _ScorePlayer; }
                set { _ScorePlayer = value; InotifyPropertyChanged("ScorePlayer"); }
            }
     
            private string _ListTyp;
            public string ListTyp
            {
                get { return _ListTyp; }
                set { _ListTyp = value; InotifyPropertyChanged("ListTyp"); }
            }
            //revoir cette proc .Le champ _PlayerName n'existe plus
            //public void Ban(string PN, string SP)
            //{
            //    _PlayerName = PN;
            //    _ScorePlayer = SP;
            //}
     
     
            #region INotifyPropertyChanged Membres
     
            public event PropertyChangedEventHandler PropertyChanged;
            private void InotifyPropertyChanged(string nameProp)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(nameProp));
                }
            }
            #endregion
        }
     
       // Classe PlayersList: une equipe(List Of Player)
        public class PlayersList : ObservableCollection<Player>
        {
            public PlayersList()
            {
            }
        }
    }
    //
    //Classe Ligue :pour representer les listes d'equipes(pour les tournois)
    // c'est un (List Of List)
    //
    // classe Ligue
    //
        public class Ligue:INotifyPropertyChanged
        {
            public Ligue()
            {
                _PlayerName = "Player Name";
            }
     
            public Ligue(string objPlayerName)
            {
                _PlayerName = objPlayerName;
                _teams = new PlayersList();
            }
     
            string _PlayerName;
            public string PlayerName 
            { 
                get { return _PlayerName; }
                set { _PlayerName = value; InotifyPropertyChanged("PlayerName");}
            }
     
            PlayersList _teams;
            public PlayersList Teams { get { return _teams; } }
     
     
            #region INotifyPropertyChanged Membres
     
            public event PropertyChangedEventHandler PropertyChanged;
            private void InotifyPropertyChanged(string nameProp)
            { 
               if (PropertyChanged !=null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(nameProp));
                }
            }
     
            #endregion
        }

    code xaml de la fentre Winform:
    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
     
    <Window x:Class="WpfListePlayersCSharp.MainWinTreeListPlayers"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:s="clr-namespace:System;assembly=mscorlib"
        xmlns:local="clr-namespace:WpfListePlayersCSharp"
        Title="MainWinTreeListPlayers" Height="300" Width="300"> 
        <Window.Resources>
            <!--classe Ligue-->
            <local:Ligue   x:Key="myLigue"/>
     
            <!--HierarchicalDataTemplate  : necessaire pour liste   Teams-->
            <HierarchicalDataTemplate 
                    DataType = "{x:Type local:Ligue}"
                    ItemsSource = "{Binding Path=Teams}">
                    <TextBlock 
                        Text="{Binding Path=PlayerName}"/>
            </HierarchicalDataTemplate>
            <!--HierarchicalDataTemplate  : necessaire pour liste   PlayersList-->
            <HierarchicalDataTemplate 
                    DataType = "{x:Type local:Player}"
                    ItemsSource = "{Binding Path=PlayersList }">
                    <TextBlock 
                        Text="{Binding Path=PlayerScore}"/>
            </HierarchicalDataTemplate>
        </Window.Resources>
        <Grid >
            <Grid.RowDefinitions>
                <RowDefinition Height="auto"></RowDefinition>
            </Grid.RowDefinitions>
            <local:TreeListView
                Grid.Row="0"> 
                    <local:TreeListViewItem 
                        x:Name="myTreeViewItem"
                        IsExpanded="True"
                        Background="LightSkyBlue"
                        Header="Ali" 
                        ItemsSource="{Binding}" >
                    </local:TreeListViewItem>
            </local:TreeListView>
     
        </Grid>
    </Window>
    code behind du winform :
    Code c# : 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
     
    using System;
    using System.Collections.Generic;
    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.Collections.ObjectModel;
    namespace WpfListePlayersCSharp
    {
        /// <summary>
        /// Logique d'interaction pour MainWinTreeListPlayers.xaml
        /// </summary>
        public partial class MainWinTreeListPlayers : Window
        {
     
            public MainWinTreeListPlayers()
            {
                InitializeComponent();
     
                //cree une liste de ligues
                _OnlineCollection = CreateCollection();
                this.DataContext = OnlineCollection; 
     
            }
            // propriete :renvoie une liste de ligues
            private ObservableCollection<Ligue> _OnlineCollection;
            public ObservableCollection<Ligue> OnlineCollection
            {
                get { return _OnlineCollection; }
                set { _OnlineCollection = value; }
            }
            //methode :cree un echantillon de liste de ligues
            private ObservableCollection<Ligue> CreateCollection()
            {
                //iniatilise collection de ligues
                _OnlineCollection = new ObservableCollection<Ligue>();
     
                //cree une ligue
                string sLigueName = string.Empty;
                Random rnd = new Random();
                Ligue l;
                sLigueName = "Player" + rnd.Next(10, 50).ToString();
                l = new Ligue(sLigueName);
     
                // cree une 1ere team dans ligue
                l.Teams.Add(new Player("Score" + rnd.Next(20, 40).ToString(), "Type" + rnd.Next(10, 20).ToString()));
                l.Teams.Add(new Player("Score" + rnd.Next(20, 40).ToString(), "Type" + rnd.Next(10, 20).ToString()));
                l.Teams.Add(new Player("Score" + rnd.Next(20, 40).ToString(), "Type" + rnd.Next(10, 20).ToString()));
                l.Teams.Add(new Player("Score" + rnd.Next(20, 40).ToString(), "Type" + rnd.Next(10, 20).ToString()));
                l.Teams.Add(new Player("Score" + rnd.Next(20, 40).ToString(), "Type" + rnd.Next(10, 20).ToString()));
                _OnlineCollection.Add(l);
     
     
                //cree une 2eme team dans ligue
                sLigueName = "Player" + rnd.Next(10, 50).ToString();
                l = new Ligue(sLigueName);
     
                l.Teams.Add(new Player("Score" + rnd.Next(50, 70).ToString(), "Type" + rnd.Next(60, 70).ToString()));
                l.Teams.Add(new Player("Score" + rnd.Next(50, 70).ToString(), "Type" + rnd.Next(60, 70).ToString()));
                l.Teams.Add(new Player("Score" + rnd.Next(50, 70).ToString(), "Type" + rnd.Next(60, 70).ToString()));
                l.Teams.Add(new Player("Score" + rnd.Next(50, 70).ToString(), "Type" + rnd.Next(60, 70).ToString()));
                l.Teams.Add(new Player("Score" + rnd.Next(50, 70).ToString(), "Type" + rnd.Next(60, 70).ToString()));
     
                _OnlineCollection.Add(l);
                return _OnlineCollection;
            }
     
     
        }
    }


    Lien MSDN(titre TreeListView Sample):

    http://www.google.fr/url?sa=t&rct=j&...zjHEx6L28WGpTw

    N.B.: l'original MSDN donne un exemple d'utilisation que j'ai trouve tres bizarre pour une fois car il utilise comme "data" les classes du .Net FrameWork....

    Enfin ce qui m'as intrigue c'est d'ou tu as "recupere" le sample(on dirait l'original MSDN trituré par quelqu'un d'autre.......)....
    Bon code................

  16. #16
    Membre habitué
    Profil pro
    Inscrit en
    Juillet 2011
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2011
    Messages : 13
    Par défaut
    A vrai dire je sais plus trop où je l'ai trouvé, c'était sur un forum anglais et la personne qui a posté les sources l'avait récupéré ailleurs.... J'essayerai de retrouver la source quand je serai chez moi car la je suis au boulot ^^
    Après qu'il l'ait trituré ou pas m'importe peu du moment que cela fonctionne ^^

    Sinon je ne suis pas sur que je peux appliquer cet exemple.
    J'ai simplement une collection d'une seule classe qui elle même contient une collection. Si cela fonctionne pour le premier noeud de mon treeview(j'ai bien mes 2 niveaux), il doit y avoir moyen de créer d'autres noeuds.
    Enfin je vais tester et on verra

  17. #17
    Membre habitué
    Profil pro
    Inscrit en
    Juillet 2011
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2011
    Messages : 13
    Par défaut
    Je viens d'essayer ca marche bien seul hic (Et oui y'en a toujours un ),
    Le niveau 1 est vide, cad :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
    + (Vide)
     + PlayersXX
          Score      ListTyp
          Score      ListTyp
          Score      ListTyp
          Score      ListTyp
     + PlayersXX
          Score      ListTyp
          Score      ListTyp
          Score      ListTyp
          Score      ListTyp
    Les "+" correspondant au expander

  18. #18
    Membre extrêmement actif
    Inscrit en
    Avril 2008
    Messages
    2 573
    Détails du profil
    Informations personnelles :
    Âge : 65

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 573
    Par défaut le niveau 1 manque
    bonjour mso54
    ben oui c'est fait express dans ce semblant (a custom view that resembles the GridView view mode that is used by ListView) de "custom treeview" de microsoft comme ils disent
    Le presenter du TreeView "normal" sert à contenir une prop Header (header de titre) definie dans le TreeViewListView "normal" .
    Ce presenter du TreeView est "squatte" maintenant par l'en-tete du "gvcc" ( GridViewColumn) qu'on a rajoute.
    code xaml de appl.resources auquel je fais allusion:
    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
     
     <Style 
                TargetType="{x:Type local:TreeListViewItem}">
                <Setter 
                    Property="Template">
                    <Setter.Value>
                        <ControlTemplate 
                            TargetType="{x:Type local:TreeListViewItem}">
                            <StackPanel>
                                <Border 
                                    Name="Bd"
                                    Background="{TemplateBinding Background}"
                                    BorderBrush="{TemplateBinding BorderBrush}"
                                    BorderThickness="{TemplateBinding BorderThickness}"
                                    Padding="{TemplateBinding Padding}" >
                                   'ici ou le bat blesse
                                   <GridViewRowPresenter 
                                        x:Name="PART_Header" 
                                        Content="{TemplateBinding Header}" 
                                        Columns="{StaticResource gvcc}"/>  
                                </Border>
                                <ItemsPresenter 
                                    x:Name="ItemsHost"/> 
                            </StackPanel>

    pour t'en convaincre encore mieux fais ceci:
    -mets la classe sur un TreeView normal.
    -mets la prop Header du treeviewItem à "Derby des champions des Champions".Observe la presentation du Header.
    Fais de meme avec la prop Header du Custom TreeListView.
    Le xaml compile mais à l'execution rien ne s'affiche...car la prop est squattee..
    bon code.............

  19. #19
    Membre habitué
    Profil pro
    Inscrit en
    Juillet 2011
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2011
    Messages : 13
    Par défaut
    Si j'ai bien compris, je suis obligé de laisser cette première ligne vide ? xD

  20. #20
    Membre extrêmement actif
    Inscrit en
    Avril 2008
    Messages
    2 573
    Détails du profil
    Informations personnelles :
    Âge : 65

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 573
    Par défaut toournoi de la BundesLigua
    bonjour mso54
    Suite à ta question sur l'entete j'ai du revoir le "sample" de plus pres.
    Le "sample" affiche effectivement le "Nom" du class "binde" (qui est un DependencyObject comme suggere par l'intellisense).
    L'astuce c'est de mettre notre type Ligue "binde" .
    Et affecter une simple valeur chaine à la prop PlayerName du type Ligue comme titre du Header du TreeListViewItem.
    Tu le fais sous la baslise <local:TreeListViewItem.

    voici le code xaml modifie :
    Code xml : 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
     
    <Window x:Class="WpfListePlayersCSharp.MainWinTreeListPlayers"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:s="clr-namespace:System;assembly=mscorlib"
        xmlns:local="clr-namespace:WpfListePlayersCSharp"
        Title="MainWinTreeListPlayers" Height="300" Width="300"> 
        <Window.Resources>
            <!--classe Ligue-->
            <local:Ligue   x:Key="myLigue"/>
     
            <!--HierarchicalDataTemplate  : necessaire pour liste   Teams-->
            <HierarchicalDataTemplate 
                    DataType = "{x:Type local:Ligue}"
                    ItemsSource = "{Binding Path=Teams}">
                    <TextBlock 
                            Text="{Binding Path=PlayerName}" />
            </HierarchicalDataTemplate>
            <!--HierarchicalDataTemplate  : necessaire pour liste   PlayersList-->
            <HierarchicalDataTemplate 
                    DataType = "{x:Type local:Player}"
                    ItemsSource = "{Binding Path=PlayersList }">
                    <TextBlock 
                        Text="{Binding Path=ScorePlayer}"/>
            </HierarchicalDataTemplate>
        </Window.Resources>
        <Grid >
            <Grid.RowDefinitions>
                <RowDefinition Height="auto"></RowDefinition>
                <RowDefinition Height="auto"></RowDefinition>
            </Grid.RowDefinitions>
            <local:TreeListView
                Grid.Row="0"> 
                    <local:TreeListViewItem 
                        x:Name="myTreeViewItem"
                        IsExpanded="True"
                        Background="LightSkyBlue"
                        ItemsSource="{Binding}" >
                        <!--SIMPLE RAJOUT xaml-->
                        <local:TreeListViewItem.Header>
                            <local:Ligue PlayerName="Championat BundesLigua"/>
                        </local:TreeListViewItem.Header>
                </local:TreeListViewItem>
            </local:TreeListView>
     
        </Grid>
    </Window>

    bon code...............

+ Répondre à la discussion
Cette discussion est résolue.
Page 1 sur 2 12 DernièreDernière

Discussions similaires

  1. TreeView Multi-Colonnes ?
    Par dark1 dans le forum Débuter
    Réponses: 3
    Dernier message: 05/04/2010, 08h15
  2. [VB.NET]ComboBox Multi-Colonnes
    Par Golzinne dans le forum Windows Forms
    Réponses: 3
    Dernier message: 02/03/2006, 18h55
  3. [VB6]Tri multi-colonnes sur tableau de structure
    Par ELGUEVEL dans le forum VB 6 et antérieur
    Réponses: 2
    Dernier message: 17/02/2006, 08h02
  4. Affichage ComboBox multi-colonnes
    Par dough29 dans le forum VB 6 et antérieur
    Réponses: 4
    Dernier message: 04/12/2005, 12h28
  5. un trombinoscope multi colonne en xsl
    Par philou44 dans le forum XSL/XSLT/XPATH
    Réponses: 6
    Dernier message: 08/10/2004, 15h38

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