c# - 将 ObservableCollection<XElement> 数据绑定(bind)到 ListBox?

标签 c# silverlight linq data-binding xelement

我正在开发一个 Silverlight 应用程序,并且想要设置 ItemsSourceListBoxObeservableCollection<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/

相关文章:

c# - 在 Visual Studio 中签署程序集时出现加密失败

c# - WCF 调用一个函数而不等待它完成它的工作?

c# - 通过 C# 的动态 XAML

C# Silverlight 3 - 以编程方式在页面之间导航?

c# - HQL 与 Linq 到对象

c# - 如何使用 linq 从保存的 guid 中随机化列表?

c# - 如何将此 SQL 查询转换为 LINQ (OVER (PARTITION BY Date))

c# - 如何获取套接字异常值

c# - 在 asp.net mvc 中打开 .aspx 文件作为 cshtml 的部分 View

c# - 确定给定数字所需的行/列