[英]Listbox does not show items c# xaml
我已經用xaml編寫了這個:
<ListBox x:Name="WorkersList"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding name}"></TextBlock> <TextBlock Text="{Binding gehalt}"></TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
然后,我編寫了一個名為“ worker”的ac#類,並將以下代碼添加到mainpage.cs中:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
List<Worker> sourceworkerlist = new List<Worker>();
sourceworkerlist.Add(new Worker { name = "Franz", gehalt = 200 });
WorkersList.DataContext = sourceworkerlist;
}
}
我運行了程序,但結果是我沒有看到listboxitem :(我做錯了什么?謝謝您的回答!
您需要將ItemsSource綁定到DataSource,或在代碼中設置ItemsSource。
WorkersList.ItemsSource = sourceworkerlist;
要么
<ListBox x:Name="WorkersList" ItemsSource="{Binding}">
如果要在后面的代碼中使用DataContext
,則XAML應該如下所示:
<ListBox x:Name="WorkersList" d:DataContext="{d:DesignInstance {x:Type local:Worker}}" ItemsSource="{Binding Mode=OneWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding name}"/>
<TextBlock Text="{Binding gehalt}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
這是完整的XAML文件:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication11" mc:Ignorable="d"
x:Class="WpfApplication11.MainWindow"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox x:Name="WorkersList" d:DataContext="{d:DesignInstance {x:Type local:Worker}}" ItemsSource="{Binding Mode=OneWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding name}"/>
<TextBlock Text="{Binding gehalt}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.