2015-07-19 119 views
1

我已经在XAML中这样写:列表框不显示项目C#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>

然后我编写了一个名为 “工人” C#类,并增加了follwing代码到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 :(我是怎么对你的答案做错了THX

?!

回答

1

如果你想在你的代码中使用DataContext背后张贴,那么你的XAML应该是这样的:

​​

这是完整的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> 
+0

感谢您的回答,它的工作原理,但我得到了一个错误在Windows 10通用平台的XAML - 即时建设:类型不支持...我如何需要更改数据上下文? –

+0

我编辑了我的答案并发布了整个XAML文件内容。您可能会缺少一些xml命名空间(xlmns)。检查你的XAML对我的。 – jsanalytics

+0

它通过保留datacontext代码行,我已经声明它在c# - >上面看起来) –

1

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

WorkersList.ItemsSource = sourceworkerlist; 

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

已经做到了 - l ook上面在我的代码 –

+0

@MatthiasHerrmann不,你没有做我没有提出的解决方案,你没有'ItemsSource =“{Binding}'也没有'WorkersList.ItemsSource = sourceworkerlist;' – FINDarkside

+0

哦,sry(它已经结束35°C在这里;)我读过它,你说得对sry –