2010-08-25 69 views
0

我正在開發Windows Phome應用程序。我有一個頁面上的以下列表框:ListBox ItemsSource綁定不起作用

<ListBox Margin="10,10,8,8" x:Name="WallList"> 
    <ListBox.ItemsPanel> 
    <ItemsPanelTemplate> 
     <StackPanel /> 
    </ItemsPanelTemplate> 
    </ListBox.ItemsPanel> 
    <ListBox.ItemTemplate> 
    <DataTemplate> 
     <Grid x:Name="ListBoxItemLayout" Background="Transparent" Margin="10"> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="0.33*"/> 
      <ColumnDefinition Width="0.77*"/> 
     </Grid.ColumnDefinitions> 
     <Image HorizontalAlignment="Left" Margin="0" Source="{Binding ImagePath}" Height="200"/> 
     <StackPanel Margin="5,0,0,0" Grid.Column="1"> 
      <TextBlock x:Name="Name" TextWrapping="Wrap" Text="{Binding Name}" Style="{StaticResource PhoneTextTitle2Style}"/> 
      <TextBlock x:Name="Comment" Margin="0,5,0,0" TextWrapping="Wrap" Text="{Binding Comment}" Style="{StaticResource PhoneTextNormalStyle}" Height="130"/> 
      <TextBlock x:Name="When" TextWrapping="Wrap" Text="{Binding When}" Style="{StaticResource PhoneTextTitle3Style}" VerticalAlignment="Bottom"/> 
     </StackPanel> 
     </Grid> 
    </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

我用這個來填補Loaded事件列表框:

this.WallList.ItemsSource = StartingWall.GetWallPosts(); 

,現在我想以編程方式添加更多的項目,當用戶寫下來TextBox上的一些文本並單擊按鈕。我想把這個文本放在評論欄裏。

我打算用默認數據填充其餘字段。

我的問題是:

如何添加更多項目到WallList ListBox?

有人建議做到以下幾點:

public ObservableCollection<WallPostEntry> MyWallPosts {get;set;} 

// Initialize MyWallPosts to whatever 

MyWallPosts.Add(new WallPostEntry("new entry")); 

<ListBox Margin="10,10,8,8" x:Name="WallList" ItemsSource="{Binding MyWallPosts}"> 

但是綁定列表框的ItemsSource不會爲我工作。我在構造函數初始化MyWallPosts,只是InitializeComponent();之前,像這樣:

public Wall() 
{ 
    MyWallPosts = StartingWall.GetWallPosts(); 
    InitializeComponent(); 
} 

有什麼建議?

謝謝。

回答

3

我看到一對夫婦奇怪的事情:

第一,你使用的的ItemsSource在一個地方具有約束力,但明確在另一個設置呢?在代碼中設置的東西會覆蓋/撤消任何綁定,這樣可能會導致一個問題(但它看起來像你把它設置爲相同的東西,所以不應該有所作爲,但我會刪除this.WallList。 ItemsSource = StartingWall.GetWallPosts();完全調用並在xaml中保留ItemsSource =「{Binding MyWallPosts}」,使用綁定的目的是擺脫這種代碼)

秒設置mywallposts並使用綁定,但不在對象本身上設置datacontext?簡單的在你的例子是隻有一個行添加到您的構造函數:

public Wall() 
{ 
    DataContext = this; 
    MyWallPosts = StartingWall.GetWallPosts(); 
    InitializeComponent(); 
} 

我的下一個建議是要簡化,直到它的工作原理。離開列表框,但註釋掉所有的項目/數據模板的,以確保你沒有一個bug在你的模板

0

他能只是增加一個 DataContext屬性此:

<ListBox Margin="10,10,8,8" x:Name="WallList" ItemsSource="{Binding MyWallPosts}"> 

所以:

<ListBox Margin="10,10,8,8" x:Name="WallList" ItemsSource="{Binding MyWallPosts}" DataContext="{Binding MyWallPosts}"> 

會有任何設置dataContext declarativelly的方法嗎?

tks, Oscar