使用DataContext的DataBinding

时间:2009-06-01 16:30:45

标签: wpf data-binding datacontext

我在这里做错了什么?我正在尝试使用DataTemplate对象中的集合创建DataContext,如下所示:

C#:

namespace StackOverflowTests
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            this.DataContext = new People();
        }
    }

    class People
    {
        public List<Person> PersonList { get; set; }

        public People()
        {
            this.PersonList = new List<Person>()
            {
                new Person(){FirstName = "Carlo", LastName = "Toribio" },
                new Person(){FirstName = "Guy", LastName = "Incognito" }
            };
        }
    }

    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

XAML:

 <Window x:Class="StackOverflowTests.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" x:Name="window1" Height="300" Width="300">
        <Window.Resources>
            <DataTemplate x:Key="peopleTemplate">
                <StackPanel>
                    <TextBlock Text="First Name" FontWeight="Bold" />
                    <TextBlock Text="{Binding PersonList.FirstName}" />
                    <TextBlock Text="Last Name" FontWeight="Bold" />
                    <TextBlock Text="{Binding PersonList.LastName}" />
                </StackPanel>
            </DataTemplate>
        </Window.Resources>
        <Grid x:Name="gridMain">
            <ItemsControl ItemsSource="{Binding}" ItemTemplate="{StaticResource peopleTemplate}" />
        </Grid>
    </Window>

通过使用继承自Collection<T>的类,我已经轻松完成了这项工作,但由于种种原因,我无法解决此问题。任何建议都非常感谢。

谢谢!

1 个答案:

答案 0 :(得分:4)

试试这个:

<Grid x:Name="gridMain">
   <ItemsControl ItemsSource="{Binding PersonList}" ItemTemplate="{StaticResource peopleTemplate}" />
 </Grid>
相关问题