【问题标题】:XAML DataBinding from code behind from XML source来自 XML 源代码的 XAML DataBinding
【发布时间】:2012-05-28 03:29:09
【问题描述】:

这是我的 XML

<?xml version="1.0" encoding="utf-8"?>
<app>
<films>
    <film name="Haha" year="2008" />
    <film name="Haha" year="2008" />
    <film name="Haha" year="2008" />
    <film name="Haha" year="2008" />
    <film name="Haha" year="2008" />
    <film name="Haha" year="2008" />
</films>
</app>

这是我的 XAML

<ListBox x:Name="listBoxControl">
<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel>
            <StackPanel>
                <TextBlock Text="{Binding Path=@name}" />
                <TextBlock Text="{Binding Path=@year}" />
            </StackPanel>
        </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

这是我的 C#

XDocument xmldoc = XDocument.Load(new StringReader(result));
listBoxControl.ItemsSource = xmldoc.Descendants("film");

在过去的几个小时里,我搜索了互联网和 Stack Overflow 问题,希望能找到解决方案。我正在做的是,从我的网站异步下载一些 XML 数据,然后将其传递给名为“listBoxControl”的 ListBox 控件。问题是“文本”字段没有在其中呈现任何文本。我在 Binding 中使用“路径”,因为不允许使用 XPath,我收到此错误:The property 'XPath' was not found in type 'Binding'

现在,我在这里做错了什么?这是一个 C# 中的 WP7.1 应用程序,使用 Visual Studio Express for Windows Phone 在 Windows 8 Consumer Preview 上运行。

【问题讨论】:

    标签: c# wpf windows-phone-7 xaml


    【解决方案1】:

    我只是创建一个类并绑定到它:

    public class Film
    {
        public string name { get; set; }
        public string year { get; set; }
    }
    
    var d = xmldoc.Descendants("film").Select(x => new Film { name = x.Attribute("name").Value, year = x.Attribute("year").Value });
    
    <TextBlock Text="{Binding name}" />
    <TextBlock Text="{Binding year}" />
    

    编辑:或匿名类型:

    var d = xmldoc.Descendants("film").Select(x => new { name = x.Attribute("name").Value, year = x.Attribute("year").Value });
    
    <TextBlock Text="{Binding name}" />
    <TextBlock Text="{Binding year}" />
    

    【讨论】:

    • 类不是必须的,可以使用匿名对象来完成。
    • 好的,我不确定这在 Windows Phone 7 上是否可行。IIRC 我听说它是​​在 WPF 中,但不是 Silverlight,所以我想我会选择更安全的选项。跨度>
    • 它仍然返回不显示任何文本,我这样做对吗:listBoxControl.ItemsSource = xmldoc.Descendants("film").Select(x =&gt; new { name = x.Attribute("name").Value, year = x.Attribute("year").Value });
    • 您是否将{Binding Path=@name} 更改为{Binding name}?如果是这样,但它仍然不起作用,请创建 Film 类并使用它。
    • 与班级一起工作。浪费在这上面的日子:3. 非常感谢!
    【解决方案2】:

    Windows Phone 不支持使用 XPath 进行绑定。

    所以解决这个问题的唯一方法是反序列化 xml 并绑定到 .NET 对象。

    确保如果您要允许用户更改数据或从您在类上实现 INotifyPropertyChanged 的​​源刷新数据,以便 UI 收到有关对象更改的通知。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-02
      • 2011-04-19
      • 2012-03-26
      • 2011-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-18
      相关资源
      最近更新 更多