0 votes

Comment faire apparaître les nœuds de l'arbre enfant dans un TreeView WPF lorsque l'on se lie à une ObservableCollection ?

Que dois-je faire ? changer dans le code suivant pour rendre le " Une section enfant "apparaît comme un enfant du nœud Première section y Deuxième section :

Le code suivant me donne une exception XamlParseException.

XAML :

<Window x:Class="TestTr32322.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:TestTr32322"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <HierarchicalDataTemplate x:Key="sectionTemplate" 
            ItemsSource="{Binding ChildSections}"
            DataType="{x:Type local:Section}">
            <TextBlock Text="{Binding Title}" />
        </HierarchicalDataTemplate>
    </Window.Resources>
    <Grid>
        <TreeView ItemsSource="{Binding Sections}" 
                  ItemTemplate="{StaticResource sectionTemplate}">
        </TreeView>
    </Grid>
</Window>

Code Behind :

using System.Windows;
using System.ComponentModel;
using System.Collections.ObjectModel;

namespace TestTr32322
{
    public partial class Window1 : Window, INotifyPropertyChanged
    {
        #region ViewModelProperty: Sections
        private ObservableCollection<Section> _sections = new ObservableCollection<Section>();
        public ObservableCollection<Section> Sections
        {
            get
            {
                return _sections;
            }

            set
            {
                _sections = value;
                OnPropertyChanged("Sections");
            }
        }
        #endregion

        public Window1()
        {
            InitializeComponent();
            DataContext = this;

            Sections = Section.GetSections();
        }

        #region INotifiedProperty Block
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

    }

    public class Section
    {
        public string Title { get; set; }
        public string Description { get; set; }
        public ObservableCollection<Section> ChildSections { get; set; }

        public static ObservableCollection<Section> GetSections()
        {
            ObservableCollection<Section> sections = new ObservableCollection<Section>();

            {
                Section section = new Section();
                section.Title = "First Section";
                section.ChildSections.Add(new Section
                {
                    Title = "A Child Section",
                    Description = "this is the description",
                    ChildSections = new ObservableCollection<Section>()
                });
                sections.Add(section);
            }

            {
                Section section = new Section();
                section.Title = "Second Section";
                section.ChildSections.Add(new Section
                {
                    Title = "A Child  Section",
                    Description = "this is the description",
                    ChildSections = new ObservableCollection<Section>()
                });
                sections.Add(section);
            }

            return sections;
        }
    }

}

1voto

Anvaka Points 9296

Il semble que vous ayez besoin de Modèle de données hiérarchiques . L'article en donne un exemple...

1voto

olli Points 1945

Jetez un coup d'œil à ceci question et la réponse acceptée. Cela devrait également vous orienter dans la bonne direction.

L'idée de base est de définir des HierarchicalDataTemplates avec une propriété ItemsSource et de les faire correspondre par type.

Dans votre cas :

<HierarchicalDataTemplate DataType="{x:Type local:Section}" 
                          ItemsSource="{Binding ChildSection}">
    <TextBlock Text="{Binding Path=Title}" />
</HierarchicalDataTemplate>

Éditer : Dans votre code, vous devez créer une nouvelle collection avant d'y ajouter une valeur :

// The new was missing and resulted in the end in your XAML Parse Exception
section.ChildSections = new ObservableCollection<Section>();
section.ChildSections.Add( /*... */);

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X