简体   繁体   中英

Listbox does not show items c# xaml

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 ac# 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!

You need to bind ItemsSource to DataSource, or set ItemsSource in the code.

WorkersList.ItemsSource = sourceworkerlist;

or

<ListBox x:Name="WorkersList" ItemsSource="{Binding}">

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM