将项目绑定到列表框

时间:2012-05-19 19:45:14

标签: c# silverlight windows-phone-7 xaml

我有一个应用程序,其中我向用户显示特定单词的含义。因此,我在前端使用了一个listBox。这是代码..

XAML:

<ListBox Background="White" Grid.Row="1" ItemsSource="{Binding}" Height="605" HorizontalAlignment="Stretch" Margin="0,90,0,0" Name="listBox1" VerticalAlignment="Top">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <StackPanel Orientation="Vertical" Height="50">
        <TextBlock Text="{Binding ActualWord}" Height="5" />
        <TextBlock Text="{Binding Meaning}"  Height="5"/>
        <TextBlock Text="{Binding Type}" Height="5"/>
        <TextBlock Text="{Binding Example}" Height="5" />
      </StackPanel>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

C#用于在后端添加单词..

listBox1.Items.Add(new WordClass()
{
    ActualWord = "Something",
    Type = "Something111",
    Meaning =  "Something222",
    Example =  "Something333"
});

问题在于代码编译,但是我看到一个空白屏幕,或者换句话说,在列表框中没有任何内容,即使我在页面的构造函数中执行此操作也是如此。

1 个答案:

答案 0 :(得分:3)

从XAML中删除ItemsSource="{Binding}"部分。由于您手动填写列表,因此您不需要它,并且可能会导致问题。

另一种选择是保持您的XAML不变,填写WordClass的集合并将其设置为DataContext

var list = new List<WordClass>();
list.Add(new WordClass()
{
    ActualWord = "Something",
    Type = "Something111",
    Meaning =  "Something222",
    Example =  "Something333"
});
...

this.DataContext = list;
相关问题