数据不会绑定WP

时间:2014-12-16 11:14:02

标签: c# windows-phone-7 windows-phone-8 windows-phone-8.1

我试图绑定来自XML文件的数据,我跟着来自mdsn和其他在线资源但是我一直收到错误,如果我将数据绑定到列表框就可以了。

  public void LoadPage()
    {
        XDocument loadedData = XDocument.Load("page01.xml");

        var data = from query in loadedData.Descendants("page")
                   select new PageReader
                   {
                       PageNumber = (int)query.Element("pnumber"),
                       ChapterTitle = (string)query.Element("ctitle"),   
                       ChapterNumber = (int)query.Element("cnumber")
                   };

        LayoutRoot.DataContext = data;
    }

和XAML

  Grid x:Name="LayoutRoot" Background="#FFFFFEFE">
    <StackPanel>
        <Grid>
            <Rectangle Fill="#FF424242" HorizontalAlignment="Left" Height="60" Stroke="Black" VerticalAlignment="Top" Width="480"/>
            <StackPanel Orientation="Horizontal">
                <TextBlock Width="100"  TextWrapping="Wrap" MaxWidth="100" MaxHeight="58" TextAlignment="Center" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="#FFB6AEAE" FontFamily="{StaticResource lob2}" Text="{Binding ChapterNumber}"/>
                <TextBlock Width="280"  TextWrapping="Wrap" MaxWidth="300" MaxHeight="58" TextAlignment="Center" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="#FFB6AEAE" FontFamily="{StaticResource lob2}" Text="{Binding ChapterTitle}"/>
                <TextBlock Width="100"  TextWrapping="Wrap" MaxWidth="100" MaxHeight="58" TextAlignment="Center" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="#FFB6AEAE" FontFamily="{StaticResource lob2}" Text="{Binding PageNumber}"/>
            </StackPanel>
        </Grid>
        <Grid Height="30"></Grid>
        <TextBlock x:Name="PageText" Height="640" ScrollViewer.VerticalScrollBarVisibility="Visible"></TextBlock>
    </StackPanel>




</Grid>

1 个答案:

答案 0 :(得分:1)

您的data类型为IEnumerable<PageReader>,这就是为什么它适用于ListBox,因为ListBox期待收藏。

如果你改变了

LayoutRoot.DataContext = data;

LayoutRoot.DataContext = data.FirstOrDefault();

至少你应该看到UI上显示了一些数据。