列表框不显示项目c#xaml

时间:2015-07-19 15:17:12

标签: c# wpf list xaml templates

我已经用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 :(我做错了什么?谢谢你的回答!

2 个答案:

答案 0 :(得分:1)

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

WorkersList.ItemsSource = sourceworkerlist;

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

答案 1 :(得分:1)

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