2009-06-01 15 views
1

ここで何が間違っていますか?私は、次のように、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>から継承するクラスを使用していますが、多くの理由からこの問題を解決することはできません。どんな提案も大歓迎です。

ありがとうございます!

答えて

4

は、このいずれかを試してみてください。

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

これは働いていました!また、DataTemplate内のおよびからPersonListを取り出しなければなりませんでした。ありがとう! – Carlo

+1

PersonListの代わりに{Binding FirstName}を持つようにpeopleTemplateを変更する必要もあります。 – Stephan

+0

@Carlo:そうです。 Sry –

関連する問題