IEnumerable和在代码背后创建StackPanels

本文关键字:创建 StackPanels 背后 代码 IEnumerable | 更新日期: 2023-09-27 18:26:05

好的,这个问题很棒,很容易理解。我想以这种方式将StackPanel实现为TreeViewItem。然而,当我尝试设置面板的Orientation时,调试人员抱怨实现IEnumerable

这是我的TreeViewItem->StackPanel实现:

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

我以前没有使用过IEnumerable,但我尝试通过导入System.Collections并将我的类设置为从IEnumerable继承来实现它。之后,我得到一个编译器错误,说我的类没有实现System.Collections.IEnumerable.GetEnumerator()

在查看了一些在线资源后,我了解到显然IEnumerable<T>包含GetEnumerable()

首先,我走对了吗?如果是,如何正确设置?

此外,如果我需要从IEnumerable<T>继承,如果我不使用某种ListTemplate,我会在<>中放入什么?

谢谢你的帮助。

请求的精确编译器错误

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

IEnumerable和在代码背后创建StackPanels

如果要初始化对象上的特定属性,则应使用Object Initialiser语法,命名要初始化的属性:

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

在您的情况下,编译器会告诉您不能使用Collection Initializer语法初始化StackPanel

此:

new StackPanel 
{
    Orientation.Horizontal
}

将产生您所看到的错误:

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

因为您试图将StackPanel初始化为System.Windows.Control.Orientation对象的集合,例如List<Orientation>

对象和集合初始化程序。