Reputation: 2790
i have written this in 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>
Then i wrote a c# class called "worker" and added the follwing code to the 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;
}
}
I ran the program but the result is I dont see the listboxitem :( what did i do wrong? Thx for your answers!
Upvotes: 1
Views: 1759
Reputation: 13188
If you want to use DataContext
in your code behind as posted, then your XAML should look like this:
<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>
This is the complete XAML file:
<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>
Upvotes: 1
Reputation: 2435
You need to bind ItemsSource to DataSource, or set ItemsSource in the code.
WorkersList.ItemsSource = sourceworkerlist;
or
<ListBox x:Name="WorkersList" ItemsSource="{Binding}">
Upvotes: 1