[英]ListBox.ItemsSource {Binding …} doesn't work, but if I set the ItemsSource in code, it's all dandy!
[英]ListBox ItemsSource Binding doesn't work
我正在開發Windows Phome應用程序。 我在頁面上有以下列表框:
<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}">
但是綁定ListBox ItemsSource對我不起作用。 我MyWallPosts
在InitializeComponent();
之前InitializeComponent();
構造函數上的MyWallPosts
InitializeComponent();
, 像這樣:
public Wall()
{
MyWallPosts = StartingWall.GetWallPosts();
InitializeComponent();
}
有什么建議嗎?
謝謝。
我看到一些奇怪的事情:
首先,您在一個地方使用itemssource綁定,但在另一個地方明確設置了它? 在代碼中設置某些內容將覆蓋/撤消任何綁定,因此可能會導致問題(但似乎您將其設置為同一事物,因此不應有所不同,但我將刪除this.WallList。 ItemsSource = StartingWall.GetWallPosts();完全調用,並將ItemsSource =“ {Binding MyWallPosts}”保留在xaml中。使用綁定的目的是擺脫這種代碼)
第二,您要設置mywallposts並使用綁定,而不是在對象本身上設置datacontext嗎? 您的示例中最簡單的方法是向構造函數添加一行:
public Wall()
{
DataContext = this;
MyWallPosts = StartingWall.GetWallPosts();
InitializeComponent();
}
我的下一個建議是簡化直到工作。 離開列表框,但注釋掉所有項目/數據模板,以確保模板中沒有錯誤
他能否為此添加一個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嗎?
tks,奧斯卡
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.