[英]How do I correctly populate a listbox from an observable collection?
我簡化了這一點只是為了展示展示問題所需要的東西 - 即雖然8個項目明顯在列表框中,但它們沒有內容,即“名稱”不顯示,它們只是空白。 如果我在設置ItemSource之后設置斷點,我可以看到源已經正確填充了集合,所以我假設我的xaml必定是錯誤的。 這是代碼和xaml:
public partial class MainPage : UserControl
{
private ObservableCollection<ToolboxItem> ToolboxItems;
public MainPage()
{
InitializeComponent();
InitToolboxItems();
lstToolbox.ItemsSource = ToolboxItems;
}
private void InitToolboxItems()
{
ToolboxItems = new ObservableCollection<ToolboxItem>();
ToolboxItems.Add(new ToolboxItem(name: "Item1"));
ToolboxItems.Add(new ToolboxItem(name: "Item2"));
ToolboxItems.Add(new ToolboxItem(name: "Item3"));
ToolboxItems.Add(new ToolboxItem(name: "Item4"));
ToolboxItems.Add(new ToolboxItem(name: "Item5"));
ToolboxItems.Add(new ToolboxItem(name: "Item6"));
ToolboxItems.Add(new ToolboxItem(name: "Item7"));
ToolboxItems.Add(new ToolboxItem(name: "Item8"));
}
public struct ToolboxItem
{
public String Name;
public ToolboxItem(String name) { Name = name; }
}
}
<Grid x:Name="LayoutRoot" Background="White">
<ListBox Name="lstToolbox" Width="200" Height="280">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" Width="100" Height="20" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
即使它不是一個真正的問題(參見前面的評論),你的問題源於你的ToolBoxItem上的字段'名稱'需要是一個能夠綁定的屬性。 所以改成它:
public string Name {get; set;}
它應該工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.