【发布时间】:2010-10-01 14:59:59
【问题描述】:
我想在 XAML 中实例化对象,并重用这些实例。我认为这应该很简单,但我被卡住了,我可能遗漏了一些明显的东西。
假设我想将猫添加到不同的房间(房间有一个包含猫类型对象的 ObservableCollection)。在 UserControl.Resources 我创建 ObjectDataProviders:
<ObjectDataProvider x:Key="Cat1" ObjectType="{x:Type local:Cat}">
<ObjectDataProvider.ConstructorParameters>
<System:String>Tom</System:String>
</ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>
<ObjectDataProvider x:Key="Cat2" ObjectType="{x:Type local:Cat}">
<ObjectDataProvider.ConstructorParameters>
<System:String>Garfield</System:String>
</ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>
<ObjectDataProvider x:Key="Cat3" ObjectType="{x:Type local:Cat}">
<ObjectDataProvider.ConstructorParameters>
<System:String>Furball</System:String>
</ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>
在我的用户控件中,我想将猫添加到房间:
<local:Room x:Name="Room1">
<local:Room.Cats>
</local:Room.Cats>
<local:Room>
<local:Room x:Name="Room2">
<local:Room.Cats>
</local:Room.Cats>
<local:Room>
将 Cat 实例添加到 ObservableCollection Room.Cats 的语法是什么?例如,我想将 Cat1 和 Cat2 添加到 Room1,将 Cat2 和 Cat3 添加到 Room2。我完全走错了吗?
【问题讨论】:
-
它可能可以通过将
<StaticResource ResourceKey="Cat1" />添加到您的猫列表中来做到这一点。由于我目前无法对此进行测试,因此我只是将其添加为评论... -
@Heinzi:我试过了,它可以编译,但是运行时它给出了 XamlParseException:“System.Windows.Data.ObjectDataProvider”类型的对象无法转换为“System.Collections.ObjectModel.ObservableCollection”类型`1[猫]'
-
我明白了。接下来我要尝试的是 (a) 在
<local:Room.Cats>内的 XAML 中创建一个 ObservableCollection(请参阅 msdn.microsoft.com/en-us/library/ms668604.aspx 中的“XAML 使用说明”),然后 (b) 将ObjectDataProvider替换为Cat(即<local:Cat Name="Garfield" x:Key="Cat1">),然后在 ObservableCollection 中添加指向 Cat 的 StaticResource。但是,这将要求您的Cat类具有无参数构造函数。
标签: wpf xaml object objectdataprovider instances