我尝试将已定义的集合TheCollection
与xaml定义的集合GreekHeroesData
ToCollectionWindow.xaml.vb:
Public Class ToCollectionWindow
Public myCollection As New ObservableCollection(Of Person)
Public ReadOnly Property TheCollection As ObservableCollection(Of Person)
Get
Return myCollection
End Get
End Property
Private Sub InitYo(sender As Object, e As EventArgs)
myCollection.Add(New Person("one"))
myCollection.Add(New Person("two"))
myCollection.Add(New Person("three"))
End Sub
End Class
ToCollectionWindow.xaml
<Window ...
DataContext="{Binding RelativeSource={RelativeSource Self}}" />
<XmlDataProvider x:Key="GreekHeroesData" XPath="GreekHeroes/Hero">
<x:XData>
<GreekHeroes xmlns="">
<Hero Name="Jason" />
<Hero Name="Hercules" />
<Hero Name="Bellerophon" />
<Hero Name="Theseus" />
<Hero Name="Odysseus" />
<Hero Name="Perseus" />
</GreekHeroes>
</x:XData>
</XmlDataProvider>
...
这是我尝试的内容:
<DataTemplate DataType="{x:Type TheCollection}">
<TextBlock Foreground="Gold" Text="{Binding Path=Name}" />
</DataTemplate>
<DataTemplate DataType="Hero">
<TextBlock Foreground="Cyan" Text="{Binding XPath=@Name}" />
</DataTemplate>
<ListBox Width="200" IsSynchronizedWithCurrentItem="True">
<ListBox.ItemsSource>
<CompositeCollection>
<CollectionContainer Collection="{Binding TheCollection}" />
<CollectionContainer Collection="{Binding Source={StaticResource GreekHeroesData}}" />
<ListBoxItem Foreground="Red">Other Listbox Item 1</ListBoxItem>
<ListBoxItem Foreground="Red">Other Listbox Item 2</ListBoxItem>
</CompositeCollection>
</ListBox.ItemsSource>
</ListBox>
构建失败:
The type reference cannot find a public type named 'TheCollection'.
答案 0 :(得分:1)
TheCollection
包含Person
个对象。因此,DataType
的{{1}}应设置为DataTemplate
,即它将应用于Person
中的所有对象:
TheCollection
答案 1 :(得分:0)
正如我在评论中所写,您必须为DataTemplate中的类型指定XAML名称空间。在你的情况下,它是ObservableCollection(Of Person)
。真正的问题是,您无法在XAML中为ObservableCollection指定通用类型。
所以你必须做一个解决方法(抱歉VB语法,我用C#开发):
namespace YourViewModelNameSpace
{
using System.Collections.ObjectModel;
public class NonGenericPersonCollection : ObservableCollection<Person> { }
//Public Class NonGenericPersonCollection Inherits ObservableCollection(Of Person)
}
Public ReadOnly Property TheCollection As NonGenericPersonCollection
<Window ...
xmlns:vm="clr-namespace:YourViewModelNameSpace" />
<DataTemplate DataType="{x:Type vm:NonGenericPersonCollection}">