列表框不显示项目c# xaml

本文关键字:xaml 项目 显示 列表 | 更新日期: 2023-09-27 18:03:39

我已经在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"的c#类,并将以下代码添加到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:(我做错了什么?谢谢你的回答!

列表框不显示项目c# xaml

如果你想在你的代码后面使用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>

您需要将ItemsSource绑定到DataSource,或者在代码中设置ItemsSource。

WorkersList.ItemsSource = sourceworkerlist;

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