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

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

C# Discussion :

WPF TreeView Recursive


Sujet :

C#

  1. #1
    Membre à l'essai
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Janvier 2015
    Messages
    14
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Gironde (Aquitaine)

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

    Informations forums :
    Inscription : Janvier 2015
    Messages : 14
    Points : 15
    Points
    15
    Par défaut WPF TreeView Recursive
    Bonjour tout le monde, j'ai un petit souci en WPF avec les treeview.

    pour commencer, voilà mes classes :

    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
    using PropertyChanged;
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Dynamic;
    using System.Text;
     
    namespace Forms.Models
    {
    [AddINotifyPropertyChangedInterface]
    public class FormData
    {
    public string Name { get; set; }
    public FieldData Field { get; set; }
    }
    }

    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
    using Forms.Enum;
    using PropertyChanged;
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Text.Json.Serialization;
    using System.Windows;
     
    namespace Forms.Models
    {
        [AddINotifyPropertyChangedInterface]
        public class FieldData
        {
     
            public FieldData()
            {
                HorizontalAlignement = EnumHorizontalAlignement.Stretch;
                VerticalAlignement = EnumVerticalAlignement.Stretch;
                Id = Guid.NewGuid();
                ForeGroundHexColor = string.Empty;
                BackgroundHexColor = string.Empty;
                BorderHexColor = string.Empty;
                DataValueType = new ObservableCollection<EnumDataValuesType>();
                fields = new ObservableCollection<FieldData>();
            }
     
            [DefaultValue("")]
            public string Name { get; set; }
     
            public Guid Id { get; set; }
            public EnumTypeComponent TypeComponent { get; set; }
            public EnumHorizontalAlignement HorizontalAlignement { get; set; }
            public EnumVerticalAlignement VerticalAlignement { get; set; }
            public EnumContentHorizontalAlignement ContentHorizontalAlignement { get; set; }
            public EnumContentVerticalAlignement ContentVerticalAlignement { get; set; }
            public EnumTextHorizontalAlignement TextHorizontalAlignement { get; set; }
            public EnumTextVerticalAlignement TextVerticalAlignement { get; set; }
            public EnumSpaceType HorizontalSpaceType { get; set; }
            public EnumSpaceType VerticalSpaceType { get; set; }
            public ObservableCollection<EnumDataValuesType> DataValueType { get; set; }
            public EnumFontWeight FontWeight { get; set; }
            public EnumFontSize FontSize { get; set; }
     
            [DefaultValue(0)]
            public int RowIndex { get; set; }
     
            [DefaultValue(0)]
            public int RowSpan { get; set; }
     
            [DefaultValue(0)]
            public int ColumnIndex { get; set; }
     
            [DefaultValue(0)]
            public int ColumnSpan { get; set; }
     
            [DefaultValue(1.0)]
            public double HorizontalSpaceUsage { get; set; }
     
            [DefaultValue(1.0)]
            public double VerticalSpaceUsage { get; set; }
     
            [DefaultValue("")]
            public string BackgroundHexColor { get; set; }
     
            [DefaultValue("")]
            public string ForeGroundHexColor { get; set; }
     
            [DefaultValue("")]
            public string BorderHexColor { get; set; }
     
            public Thickness Margin { get; set; }
     
            public Thickness BorderThickness { get; set; }
     
            private ObservableCollection<FieldData> fields;
            public ObservableCollection<FieldData> Fields
            {
                get
                {
                    if (fields == null) fields = new ObservableCollection<FieldData>();
                    return fields;
                }
                set => fields = value;
            }
     
            private DataValues data;
            public DataValues Data
            {
                get
                {
                    if (data == null) data = new DataValues();
                    return data;
                }
     
                set => data = value;
            }
     
     
            public bool ShouldSerializeFields()
            {
                return Fields.Count > 0;
            }
     
            public bool ShouldSerializeData()
            {
                return
                    Data.BoolValue != default ||
                    Data.ByteValue != default ||
                    Data.DateValue != default ||
                    Data.FloatValue != default ||
                    Data.GroupValue != default ||
                    Data.IntValue != default ||
                    (Data.StringValue != default && !string.IsNullOrEmpty(Data.StringValue));
            }
     
            public override string ToString()
            {
                return Name;
            }
        }
    }
    Comme on peut le voir, FormData posséde un propriété de type fieldata, qui lui se contient de manière récursive,

    je souhaiterai afficher le treeview de la manière suivante :

    Formdata
    -----Field(champs unique de formdata)
    ----------Fields(champ issu de Field)
    ---------------Fields....(Champs par récursion)

    et ça c'est ma fenètre :
    behind
    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
    using Forms.Models;
    using Forms.Tools;
    using Newtonsoft.Json;
    using PropertyChanged;
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Linq;
    using System.Text;
    using System.Text.Json;
    using System.Threading;
    using System.Threading.Tasks;
    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;
     
    namespace Forms
    {
    [AddINotifyPropertyChangedInterface]
    public partial class FormsGenerator : Window
    {
    GeneratorHelpers generator = new GeneratorHelpers();
    public FormData Formulaire { get; set; }
    public ObservableCollection<FormData> ListeFormulaire { get; set; }
     
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
    Formulaire = generator.GenerateData();
    generator.GenerateGrid(Formulaire.Field, GridRendu);
    ListeFormulaire = new ObservableCollection<FormData>() { Formulaire, new FormData() { Name = "test" } };
    }
     
    private void Button_Click(object sender, RoutedEventArgs e)
    {
    ClearGrid();
    generator.GenerateGrid(Formulaire.Field, GridRendu);
     
    }
     
    private void ClearGrid()
    {
    GridRendu.Children.Clear();
    GridRendu.ColumnDefinitions.Clear();
    GridRendu.RowDefinitions.Clear();
    }
     
    private void ButtonAddChildren_Click(object sender, RoutedEventArgs e)
    {
    FieldData field = (sender as Button).DataContext as FieldData;
    var child = new FieldData() { Name = "Unknow" };
    field.Fields.Add(child);
    }
     
    private void ButtonRemoveChildren_Click(object sender, RoutedEventArgs e)
    {
     
    }
     
    }
    }
    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
    <Window x:Class="Forms.FormsGenerator"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:Models="clr-namespace:Forms.Models"
            xmlns:UserControls="clr-namespace:Forms.UserControls"
            xmlns:local="clr-namespace:Forms"
            mc:Ignorable="d"
            Title="FormsGenerator" Height="1080" Width="1920" WindowState="Maximized" Loaded="Window_Loaded"
            x:Name="CurrentWindow">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="0.75*"/>
                <ColumnDefinition Width="2*"/>
            </Grid.ColumnDefinitions>
            <Grid Grid.Column="0" x:Name="gridJson" Background="White">
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <TreeView Grid.Row="0" x:Name="TreeViewField" Margin="10" ItemsSource="{Binding  ElementName=CurrentWindow,Path=ListeFormulaire,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
                    <TreeView.ItemTemplate>
                        <HierarchicalDataTemplate DataType="{x:Type Models:FormData}" >
                            <TextBlock Text="{Binding Name}"/>
                            <HierarchicalDataTemplate.ItemTemplate>
                                <HierarchicalDataTemplate  DataType="{x:Type Models:FieldData}"  ItemsSource="{Binding Field}">
                                    <TextBlock Text="{Binding Name}"/>
                                    <HierarchicalDataTemplate.ItemTemplate>
                                        <HierarchicalDataTemplate DataType="{x:Type Models:FieldData}" ItemsSource="{Binding Fields,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" >
                                            <TextBlock Text="{Binding Name}"/>
                                        </HierarchicalDataTemplate>
                                    </HierarchicalDataTemplate.ItemTemplate>
                                </HierarchicalDataTemplate>
                            </HierarchicalDataTemplate.ItemTemplate>
                        </HierarchicalDataTemplate>
                    </TreeView.ItemTemplate>
                </TreeView>
                <UserControls:UserControlEditFormData Grid.Row="1" DataContext="{Binding ElementName=TreeViewField,Path=SelectedItem}"/>
            </Grid>
            <Grid Grid.Column="1" Background="#2980b9">
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="auto"/>
                </Grid.RowDefinitions>
                <Grid Margin="20" Grid.Row="0" x:Name="GridRendu"/>
                <Button Grid.Row="1" Content="Generer rendu" Width="200" HorizontalAlignment="Right" Margin="10" Height="30" Click="Button_Click"/>
            </Grid>
        </Grid>
    </Window>

    Je pensais avoir trouvé la solution avec ça : https://stackoverflow.com/questions/...aldatatemplate

    mais c'est visiblement une mauvaise pioche... des idées ?

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

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 441
    Points
    4 441
    Par défaut
    bonjour
    Apparemment tu ne t'entends pas avec le TreeView Wpf.
    Il suffit de specifier les HierarchicalDataTemplates necesaires et les liaisons (binding) approprié
    ton code revu avec un exemple recursif (un tree ou arbre de FieldData)




    1/ tes class Data


    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
    namespace WpfTvRecursif
    {
     
        public class VMBase : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
     
            public void OnPropertyChanged(string propname)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propname));
                }
            }
        }  
     
        public class FormData:VMBase
        {
            private string name;
            public string Name 
            {
                get { return name; }
                set { name = value; OnPropertyChanged("Name"); }
            }
     
            private FieldData fieldData;
            public FieldData FieldData
            {
                get { return fieldData; }
                set { fieldData = value; OnPropertyChanged("FieldData");}
            }
            public FormData()
            {
                Name = "nothing";
                FieldData = new FieldData();
     
            }
        }
     
    }
     
    public class FieldData:VMBase 
        {
            private  string name;
            public string Name
            {
                get { return name; }
                set { name = value; OnPropertyChanged("Name"); }
            }
            private int id;
            public int Id
            {
                get { return id; }
                set { id = value; OnPropertyChanged("Id"); }
            }
            private ObservableCollection<FieldData> fields;
            public ObservableCollection<FieldData> Fields
            {
                get
                {
                    if (fields == null) fields = new ObservableCollection<FieldData>();
                    return fields;
                }
                set { fields = value; OnPropertyChanged("Fields"); }
            }
            public FieldData()
            {
                Name = "nothing";
                Id = 100;
     
            }
        }
     
      public class ListFormData :ObservableCollection <FormData>
        {
            //à titre d'illustration une procedure recursive est utilisée 
            //pour creer un arbre de FieldData
            private int limitDepth = 3;// 
            private int maxChild = 2;
     
            // 2 variables de travail
            private FormData frmData;
            private FieldData fld;
            public ListFormData()
            {
     
                for (int i = 1; i < 3; i++)
                {
                    frmData = new FormData() { Name = "Frm" + i.ToString() };
                    for (int j = 0; j < maxChild; j++)
                    {
                        fld = new FieldData() { Name = "Fld" + j.ToString(), Id = j };
                        AddNodes(fld, 0);
                    }
                    this.Add(frmData);
                }
            }
            private void AddNodes(FieldData field, int depth)
            {
                if (depth > limitDepth) return;
                AddNode(field, depth + 1);
                foreach (var item in field.Fields)
                {
                    AddNodes(item, depth + 1);
                }
            }
            private void AddNode(FieldData field, int depth)
            {
                for (int i = 1; i <= maxChild; i++)
                {
                    field.Fields.Add(new FieldData() { Name = "Fld" + depth.ToString() + i.ToString() ,Id = i}); ;
                }
            }
        }


    2/ code du simple form user:
    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
    <Window x:Class="WpfTvRecursif.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfTvRecursif" 
            Title="MainWindow" Height="350" Width="525">
        <Window.DataContext>
            <local:ListFormData></local:ListFormData>
        </Window.DataContext>
        <Window.Resources>
            <Style TargetType="{x:Type TreeViewItem}">
                <Setter Property="IsExpanded" Value="true"  />
            </Style>
            <!--hierachie principale-->
            <HierarchicalDataTemplate 
                DataType="{x:Type local:FormData}"
                ItemsSource="{Binding Path=FieldData.Fields}">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Margin="5" Text="{Binding Name }"/>
                    <TextBlock Margin="5" Text="{Binding Id }"/>
                </StackPanel>
            </HierarchicalDataTemplate>
            <!--hierachie secondaire  -->
            <!--etant donné la recursion aucun  DataTemplate n'est necessaire-->
            <HierarchicalDataTemplate
                DataType="{x:Type local:FieldData}"
                ItemsSource="{Binding Path=FieldData.Fields}">
                <StackPanel Orientation="Horizontal" >
                    <TextBlock Margin="5" Text="{Binding Name}"/>
                    <TextBlock Margin="5" Text="{Binding Id}"/>
                </StackPanel>
            </HierarchicalDataTemplate>
        </Window.Resources> 
            <Grid>
            <TreeView  
                ItemsSource="{Binding }">
            </TreeView>
        </Grid>
    </Window>
    bon code....

Discussions similaires

  1. [WPF] TreeView avec CheckBox en cascades?
    Par bakonu dans le forum Windows Presentation Foundation
    Réponses: 5
    Dernier message: 18/07/2008, 10h59
  2. WPF Treeview et Customization
    Par EzecKiel dans le forum Windows Presentation Foundation
    Réponses: 8
    Dernier message: 27/05/2008, 16h38
  3. [WPF] TreeView & SelectedItem
    Par UNi[FR] dans le forum Windows Presentation Foundation
    Réponses: 15
    Dernier message: 18/02/2008, 10h16
  4. Réponses: 11
    Dernier message: 10/12/2007, 13h47
  5. [WPF] TreeView et contextMenu
    Par binoo dans le forum Windows Presentation Foundation
    Réponses: 4
    Dernier message: 09/11/2007, 15h29

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