【问题标题】:Binding data in Hub Control in Windows universal apps with list items在 Windows 通用应用程序中使用列表项绑定集线器控件中的数据
【发布时间】:2014-10-26 05:42:20
【问题描述】:

您好,我的列表定义如下

public class Article
{
    public string title { get; set; }
    public string author { get; set; }
    public string content { get; set; }
}
public static List<Article> articles = new List<Article>();

我使用异步方法从服务器获取xml数据并解析它。

private async void Button_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
{
        //Progress Bar
        prg.Visibility = Visibility.Visible;

        string xml = string.Empty;            
        Uri url = new Uri("http://someurl.com/someting.php");
        HttpClient httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml");
        var response = await httpClient.GetAsync(url);
        using (var responseStream = await response.Content.ReadAsStreamAsync())
        using (var streamReader = new StreamReader(responseStream))
        {
            xml = streamReader.ReadToEnd();
        }
        try
        {
            Debug.WriteLine("Parsing to start");
            string eve = "article";
            XDocument loadedData = XDocument.Parse(xml);
            foreach (var item in loadedData.Descendants(eve))
            {

                try
                {
                    Article c = new Article();
                    c.title = item.Element("title").Value;
                    c.author = item.Element("author").Value;
                    c.content = item.Element("content").Value;
                    articles.Add(c);
                }
                catch
                {
                    Debug.WriteLine("Failed");
                }

            }

            Debug.WriteLine("About to add items");
            articlelist.DataContext = articles;
            Debug.WriteLine("Items added");
        }
        catch
        {
            Debug.WriteLine("Parsing Failed");
        }
        prg.Visibility = Visibility.Collapsed;

}

下面是 xaml UI 元素

<Page
   x:Class="Airtrixz.MainPage"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:local="using:Airtrixz"
   xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   mc:Ignorable="d"
   Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <ProgressBar Grid.Row="0" IsIndeterminate="True" Foreground="{StaticResource PhoneAccentBrush}" VerticalAlignment="Top" Height="16" x:Name="prg" Visibility="Collapsed"/>
        <TextBlock Text="Airtrixz" Margin="10,0,0,0" FontSize="30"/>

       <Hub Margin="0,50" Foreground="White">
           <HubSection Header="posts" x:Name="articlelist" >
               <DataTemplate>
                   <StackPanel Background="Transparent">
                    <TextBlock Foreground="White" Text="{Binding title}" Height="25" />
                    <TextBlock Foreground="White" Text="{Binding author}" Height="25"/>
                    <TextBlock Foreground="White" Text="{Binding content}" Height="25"/>
                </StackPanel>
               </DataTemplate>

            </HubSection>
        </Hub>

       <Button Width="100" Margin="10,10,0,0" VerticalAlignment="Bottom" Height="50" Tapped="Button_Tapped" Content="Load"/>
    </Grid>
</Page>

articlelist.DataContext=articles 似乎没问题。但是没有显示任何列表项,并且 HubSection 中的标题、内容和作者属性出现以下错误

错误:BindingExpression 路径错误:在 'System.Collections.Generic.List1[[Airtrixz.MainPage+Article, Airtirxz.WindowsPhone, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e'. BindingExpression: Path='title' DataItem='System.Collections.Generic.List1[[Airtrixz.MainPage+Article、Airtirxz.WindowsPhone、Version=1.0.0.0、Culture=neutral、 PublicKeyToken=null]],mscorlib,版本=4.0.0.0,文化=中性,PublicKeyToken=7cec85d7bea7798e';目标元素是'Windows.UI.Xaml.Controls.TextBlock'(名称='null');目标属性是“文本”(类型“字符串”)

谁能给我一个解决方案?

【问题讨论】:

  • 仅查看错误消息,您的TextBoxes 的上下文似乎是Articles 的列表,而不是单个对象。你不需要某种ItemsControl 来循环你的集合来填充HubSections 吗?
  • @Jerrington 我是这里的初学者,您介意详细说明如何使用 ItemsControl 填充 HubSections 吗?

标签: c# wpf xaml win-universal-app


【解决方案1】:

由于您的 HubSection 的 DataTemplate 是 StackPanel,它只会显示单个对象,而不是整个文章列表。为此,您需要一个 ListBox 或 ListView。这就是您收到 Bindings 错误的原因;它试图在您的列表中找到“标题”属性,这当然不存在。试试这个:

<Hub Margin="0,50" Foreground="White">
    <HubSection Header="posts" x:Name="articlelist" >
        <DataTemplate>
            <ListView ItemsSource="{Binding}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Background="Transparent">
                            <TextBlock Foreground="White" Text="{Binding title}" Height="25" />
                            <TextBlock Foreground="White" Text="{Binding author}" Height="25"/>
                            <TextBlock Foreground="White" Text="{Binding content}" Height="25"/>
                        </StackPanel>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </DataTemplate>
    </HubSection>
</Hub>

这会将ListViewItemsSource 绑定到HubSectionDataContext,您在Button_Tapped 回调中将其设置为articles,所以它应该都能正常工作。以任何方式发布回复,我可以尝试帮助调试更多。

【讨论】:

  • 它确实有效,现在没有错误。但是每个列表视图项中的输出是 App2.MainPage+Aritcle。 [链接]imgur.com/7vHJnBE 使用此链接可以更好地了解问题。
  • 很高兴为您提供帮助 :) XAML 和绑定在您刚开始使用它时可能会非常混乱。
【解决方案2】:

不确定我是否应该将其作为答案,因为我从未使用过 Hub 控件,但我的猜测是 HubSections 必须像这样填充:

<ItemsControl ItemsSource="{Binding}">
   <ItemsControl.ItemTemplate>
      <DataTemplate>
         <HubSection Header="posts">
            <DataTemplate>
               <StackPanel Background="Transparent">
                <TextBlock Foreground="White" Text="{Binding title}" Height="25" />
                <TextBlock Foreground="White" Text="{Binding author}" Height="25"/>
                <TextBlock Foreground="White" Text="{Binding content}" Height="25"/>
             </StackPanel>
           </DataTemplate>
         </HubSection>
      </DataTemplate>
   </ItemsControl.ItemTemplate>
</ItemsControl>

【讨论】:

  • 错误:无法将指定的值分配给集合。预期以下类型:“HubSection”。错误:无法将“ItemsControl”类型的值添加到“IList`1”类型的集合或字典中。它给出了上述错误。
猜你喜欢
  • 1970-01-01
  • 2015-01-21
  • 1970-01-01
  • 2011-05-22
  • 1970-01-01
  • 2014-04-29
  • 1970-01-01
  • 2013-10-05
  • 2016-01-08
相关资源
最近更新 更多