简体   繁体   English

将ListView绑定到三层深的对象列表

[英]Bind ListView to a List of objects three levels deep

I am working on a Windows Phone 8.1 application (non SL) and I have the following model: 我正在使用Windows Phone 8.1应用程序(非SL),并且具有以下模型:

Quiz
    -- Question
        -- Text
        -- Options
            Options 1 (name, value)
            Options 2 (name, value)
            Options 3 (name, value)

In my XAML page, I have a ListView. 在我的XAML页面中,我有一个ListView。 I am attempting to bind the list of options to it, like so: 我试图将选项列表绑定到它,如下所示:

<Page.Resources>
    <DataTemplate x:Key="TemplateOptions">
        <TextBlock Text="{ Binding Name }" FontSize="25" HorizontalAlignment="Center" VerticalAlignment="Center" TextAlignment="Center" Foreground="Black" FontWeight="Bold"></TextBlock>
    </DataTemplate>
</Page.Resources>

<ListView Grid.Row="1" ItemsSource="{Binding Question.Options}" ItemTemplate="{StaticResource TemplateOptions}"></ListView>

But this isn't working! 但这不起作用! When I run the application, the list is empty. 当我运行该应用程序时,该列表为空。 What am I doing wrong? 我究竟做错了什么?

Thanks 谢谢

I got it to work like this: 我让它像这样工作:

CodeBehind: 代码背后:

public sealed partial class MainPage : Page
{

    public class Quiz
    {
        public Question Question { get; set; }
    }

    public MainPage()
    {
        this.InitializeComponent();

        var options = new List<Option>();
        options.Add(new Option { name = "foo", value = "bar" });
        options.Add(new Option { name = "foo", value = "bar" });
        options.Add(new Option { name = "foo", value = "bar" });
        options.Add(new Option { name = "foo", value = "bar" });

        var question = new Question
        {
            Text = "Question 1",
            Options = new ObservableCollection<Option>(options)
        };


        this.DataContext = new Quiz { Question = question };
    }

    /// <summary>
    /// Invoked when this page is about to be displayed in a Frame.
    /// </summary>
    /// <param name="e">Event data that describes how this page was reached.
    /// This parameter is typically used to configure the page.</param>
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {

    }
}

public class Question
{
    public string Text { get; set; }
    public ObservableCollection<Option> Options { get; set; }
}

public class Option
{
    public string name { get; set; }
    public string value { get; set; }

}

MainPage.xaml MainPage.xaml

<Page.Resources>
    <DataTemplate x:Key="TemplateOptions">
        <TextBlock Text="{Binding name}" FontSize="25" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="Black" FontWeight="Bold"></TextBlock>
    </DataTemplate>
</Page.Resources>
<Grid Background="White">
    <ListView ItemsSource="{Binding Question.Options}" ItemTemplate="{StaticResource TemplateOptions}"></ListView>
</Grid>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM