2011-12-16 145 views
0

我將MyListBox綁定到MyObject實例列表。 MyObject包含一個名爲TextField的字符串字段。我想將listBox中的每個項目綁定到MyObject.TextField。我的代碼如下,但它不起作用。C#WPF DataTemplate綁定

<ListBox Name="MyListBox"> 
    <ListBox.ItemTemplate> 
      <DataTemplate>     
        <TextBlock Text="{Binding Path=TextField}"></TextBlock> 
      </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

什麼是正確的方法來做到這一點?

解決:我對象的類文本字段是不是屬性

+1

要麼發佈正確的答案,並接受它或刪除問題。 – 2011-12-17 02:49:52

回答

2

確保設定ListBox的ItemsSource

<ListBox Name="MyListBox" ItemsSource="{Binding theList}"> 
    <ListBox.ItemTemplate> 
      <DataTemplate>     
        <TextBlock Text="{Binding TextField}" /> 
      </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 
+0

以這種方式它甚至不綁定到列表。 – HelloWorld 2011-12-16 18:32:15

+0

@HelloWorld您是否正確設置了Window/UserControl的DataContext? – 2011-12-16 18:33:22

-2

編輯:我試過的解決方案在VS 2010 ...點擊這裏是代碼

首先你創建自己的類,例如人類

class Person 
{ 

    public Person(String name) 
    { 
     this.name = name; 
    } 

    String name; 
    public String Name 
    { 
     get { return name; } 
     set { name = value; } 
    } 
} 

,那麼你在XAML中創建列表框就像在XAML路徑此

<ListBox Height="222" HorizontalAlignment="Left" Margin="105,28,0,0" Name="listBox1" VerticalAlignment="Top" Width="120" ItemsSource="{Binding}" > 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <TextBlock Text="{Binding Path=Name}" /> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 

注=名稱是您要在列表框中

在代碼隱藏文件

顯示,輸入以下代碼屬性

 List<Person> persons = new List<Person>(); 
     persons.Add(new Person("person 1")); 
     persons.Add(new Person("person 2"));