【问题标题】:DataBinding with DataContext与 DataContext 的数据绑定
【发布时间】:2009-06-01 16:30:45
【问题描述】:

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

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&lt;T&gt; 的类,我已经轻松完成了这项工作,但由于许多原因,我无法这样做来解决这个问题。非常感谢任何建议。

谢谢!

【问题讨论】:

    标签: wpf data-binding datacontext


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 这成功了!我还必须从 DataTemplate 中的 中取出 PersonList。谢谢!
    • 您还需要将 peopleTemplate 更改为只有 {Binding FirstName} 而不是 PersonList
    猜你喜欢
    • 2011-11-28
    • 2012-12-25
    • 1970-01-01
    • 2011-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    相关资源
    最近更新 更多