WPF-如何访问窗口代码隐藏中的公共字段类型
我尝试将已定义的集合集合集合与xaml定义的集合GreekHeroesData结合起来 ToCollectionWindow.xaml.vb:WPF-如何访问窗口代码隐藏中的公共字段类型,wpf,vb.net,Wpf,Vb.net,我尝试将已定义的集合集合集合与xaml定义的集合GreekHeroesData结合起来 ToCollectionWindow.xaml.vb: Public Class ToCollectionWindow Public myCollection As New ObservableCollection(Of Person) Public ReadOnly Property TheCollection As ObservableCollection(Of Person)
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>
它在生成时失败:
类型引用找不到名为“TheCollection”的公共类型。正如我在注释中所写,您必须为该类型指定XAML命名空间,该命名空间应在DataTemplate中处理。在你的情况下,这是一个可观察到的人的集合。真正的问题是,不能在XAML中为ObservableCollection指定泛型类型。 所以你必须做一个变通的工作对不起VB语法,我用C开发: 集合包含Person对象。因此,DataTemplate的数据类型应设置为Person,即它将应用于集合中的所有对象:
您设置了DataContext吗?@DavidSdot抱歉,我忘了在这里包括它:DataContext={Binding RelativeSource={RelativeSource Self}是在Window元素上设置的。请参阅更新的帖子。您必须为集合类型提供名称空间,当然它应该是集合类型的类型,而不是对象中的属性。抱歉,我不太明白这一点。。Collection是一个属性,返回类型为ObservableCollectionOf Person的字段myCollection。该属性应该如何或为什么具有名称空间?你是说XML名称空间吗?是的!问题是您使用泛型集合。因此,不能为集合指定泛型类型。请参阅解决方法:
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}">
<DataTemplate DataType="{x:Type local:Person}">
<TextBlock Foreground="Gold" Text="{Binding Path=Name}" />
</DataTemplate>