好的,this question非常棒,易于理解。我想以一种确切的方式将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()
。
在查看了几个online resources后,我了解到显然IEnumerable<T>
包含GetEnumerable()
。
首先,我是在正确的轨道上吗?如果是这样,我该如何正确设置此设置?
此外,如果我需要继承IEnumerable<T>
,如果我不使用某种<>
或List
,我会在Template
中添加什么?
感谢您的帮助。
请求的确切编译器错误
'Project.Folder.Class' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'
答案 0 :(得分:1)
如果要初始化对象的特定属性,则应通过命名要初始化的属性来使用Object Initialiser
语法:
TreeViewItem newNode = new TreeViewItem()
{
Header = new StackPanel { Orientation = Orientation.Horizontal}
};
在您的情况下,编译器告诉您无法使用StackPanel
语法初始化Collection Initializer
。
此:
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>
。