c# - 数据上下文 Windows 8 应用程序

标签 c# xaml

这是我第一次创建 Windows 8 应用程序,只是因为我必须为学校项目创建。我对 xaml 中的数据绑定(bind)等并不陌生,但在创建 W8 应用程序时是否有所不同,因为它不像我平时那样工作。

XAML 代码:(我的数据模板在 )

<ItemsControl ItemTemplate="{StaticResource test}" DataContext="{Binding ListLineup}">
<DataTemplate x:Key="test">
        <StackPanel>
            <TextBlock Text="{Binding Date}"></TextBlock>
        </StackPanel>
    </DataTemplate>

模型:(从 JSON 文件加载的数据)

public class LineUp
{
    public string Id { get; set; }
    public string Date { get; set; }
    public string From { get; set; }
    public string Until { get; set; }

    public LineUp(string id, string date, string from, string until)
    {
        this.Id = id;
        this.Date = date;
        this.From = from;
        this.Until = until;
    }

    public static async Task<List<LineUp>> GetLineUp()
    {
        List<LineUp> lineup = new List<LineUp>();
        using (HttpClient client = new HttpClient())
        {
            string url = @"http://localhost:28603/api/LineUp";
            Uri uri = new Uri(url);
            using (HttpResponseMessage response = await client.GetAsync(uri))
            {
                if (response.IsSuccessStatusCode)
                {
                    string content = await response.Content.ReadAsStringAsync();
                    content = "{'lineups':" + content + "}";

                    ListLineUp CollectionOfLineUps = await JsonConvert.DeserializeObjectAsync<ListLineUp>(content);
                    foreach (LineUp newLineup in CollectionOfLineUps.lineups)
                    {
                        lineup.Add(newLineup);
                    }
                }
                else
                {
                    Debug.WriteLine("Exception when getting the LineUps. API is down ");
                }
            }
        }
        return lineup;
    }
}

public class ListLineUp
{
    public List<LineUp> lineups { get; set; } 
}

XAML 背后的代码:

 public async void GetAllNeededLists()
    {
        ListLineup = await LineUp.GetLineUp();
        foreach (var lu in ListLineup)
        {
            Debug.WriteLine(lu.Date);
        }

    }

运行时,我会在调试窗口中获取所有数据以及我的日期。 运行应用程序时出现文本 block ,但其中没有内容。

最佳答案

要在 ItemsControl 中显示项目,您需要使用 IEnumerable 对象设置 ItemsSource 属性。

<ListView ItemsSource="{Binding lineups}"/>

并将您的 ListLineUp 对象设置到 ListView 上方的 DataContext 中。

要设置 DataTemplate,请使用 ItemTemplate 属性。

<ListView.ItemTemplate>
    <DataTemplate>...</DataTemplate>
</ListView.ItemTemplate>

关于c# - 数据上下文 Windows 8 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20912609/

相关文章:

c# - EF Code First 使用现有的 MySql 数据库

C# 客户端无法背靠背触发服务器

.net - 错误 "Tag does not exist in XML namespace"

c# - WPF 中的线条效果

c# - DataGrid SortDirection 被忽略

c# - 最小起订量:我可以验证一个 setter 只被调用了 N 次吗?

c# - 从 winforms 应用程序中的子窗体关闭主窗体

c# - Rowcommand 触发前 Gridview 中 LinkBut​​ton 的确认框

c# - ItemsControl中子元素的加权分布

c# - 如何为 dataTemplate 中的文本 block 动态设置工具提示?