Question

Okay so this question is awesome and easy to understand. I would like to implement a StackPanel into a TreeViewItem in that exact way. However, when I try to set the Orientation of the panel, the comiler complains about implementing IEnumerable.

Here's my TreeViewItem -> StackPanel implementation:

public static TreeViewItem newnode = new TreeViewItem()
{
       Header = new StackPanel {
           Orientation.Horizontal
       }
};

I haven't worked with IEnumerable before, but I tried implementing it by importing System.Collections and then setting my class to inherit from IEnumerable. After doing that I get a compiler error that says my class does not implement System.Collections.IEnumerable.GetEnumerator().

After looking at a few online resources I learned that apparently IEnumerable<T> contains GetEnumerable().

First of all, am I on the right track? If so, how do I get this setup correctly?

Also, if I need to inherit from IEnumerable<T> what would I put in the <> if I am not working with some kind of List or Template?

Thank for your help.

Exact Compiler Error as Requested

'Project.Folder.Class' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'

Was it helpful?

Solution

If you want to initialise a specific property on an object, you should use the Object Initialiser syntax by naming the property you wish to initialise:

TreeViewItem newNode = new TreeViewItem()
{
    Header = new StackPanel { Orientation = Orientation.Horizontal}
};

In your case, the compiler is telling you that you can't initialise a StackPanel using the Collection Initializer syntax.

This:

new StackPanel 
{
    Orientation.Horizontal
}

Will produce the error you're seeing:

Error   1   Cannot initialize type 'System.Windows.Controls.StackPanel' with a collection initializer because it does not implement 'System.Collections.IEnumerable'

Because you're trying to initialise the StackPanel as though it was a collection of System.Windows.Control.Orientation objects, e.g. List<Orientation>.

Object and Collection Initializers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top