2011-12-16 143 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"));