我正在开发一个 Silverlight 应用程序,并且想要设置 ItemsSource
的ListBox
至ObeservableCollection<XElement>
并且仍然能够使用 Binding Path=Element[name].Value
获取数据模板值的语法。我可以成功绑定(bind),但 Element[] 语法不起作用。它只是呈现空。例如,这不起作用:
<DataTemplate x:Key="SearchResultsTemplate">
<ListBox ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=Element[key].Value}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DataTemplate>
但奇怪的是,类似这样的东西确实会渲染内容,这告诉我一切都在某种程度上绑定(bind),但有些东西阻止我使用 Element 动态属性:
<DataTemplate x:Key="SearchResultsTemplate">
<ListBox ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=FirstNode}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DataTemplate>
我做错了什么?
最佳答案
Element
伪属性仅在 .NET 桌面版本中可用。它依赖于类型描述符系统,该系统是 Silverlight 中缺少的 .NET Framework 的组成部分之一。
在完整的.NET框架中,XElement
有一个[TypeDescriptionProvider(typeof(XTypeDescriptionProvider<XElement>))]
属性,这就是那些Element
和其他伪属性暴露于数据绑定(bind)。 XElement
的 Silverlight 版本中不存在此属性。 (它不能出现,因为 Silverlight 不提供 TypeDescriptionProvider
的定义,或该属性背后的任何关联机制。
Silverlight 不提供绑定(bind)到 XML 内容的直接方法。 (它也不支持 XPath,这是 WPF 中流行的另一种解决方案。)您可以查看 Binding XML in Silverlight without nominal classes其中链接到 Graham Murray 撰写的一篇文章,该文章展示了如何动态生成可绑定(bind)类型。
不过,这是一个相对复杂的解决方案。我想我只需为包含我想要的数据的 XML 编写一个包装器类型,然后使用 LINQ to XML 从 XML 填充这些包装器。
关于c# - 将 ObservableCollection<XElement> 数据绑定(bind)到 ListBox?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4437949/