2009-02-03 65 views
10

我有一个列表框,我想遍历我的Foo对象中的一组酒吧。如何正确绑定WPF中的ListBoxItem?

<ListBox DataContext="{Binding Path=Foo.Bars}" > 
    <ListBox.Items> 
     <ListBoxItem> 
      <ContentControl DataContext="{Binding Path=.}" /> 
     </ListBoxItem> 
    </ListBox.Items> 
</ListBox> 

这是我想要使用的数据素材。

<DataTemplate DataType="{x:Type Bar}"> 
     <Label Content="hello stackoverflow" /> 
</DataTemplate> 

如果我探听( - >使用工具史努比检查)我的申请,我注意到整个集合酒吧绑定到ContentControl中,在短短1代替。

我该如何正确绑定,以便对集合的迭代进行得很好?

回答

3

首先你的命名空间添加到Window元素(智能感知):

xmlns:local="clr-namespace:yourenamespace" 

那么下面XAML(在Window.Resources是一个干净的方式做到这一点):

<Window.Resources> 

     <ObjectDataProvider x:Key="DataProvider" ObjectType="{x:Type local:Foo}"/> 

     <DataTemplate x:Key="Template" > 
      <TextBlock Text="{Binding Bar}"/> 
     </DataTemplate> 

    </Window.Resources> 

放置Listbox

<ListBox DataContext="{Binding Source={StaticResource DataProvider}}" ItemsSource="{Binding Bars}" ItemTemplate="DynamicResource Template" /> 

但是,它d在你的代码隐藏对象中,你必须设置一个构造函数来初始化你的对象中的公共属性,最好是ObservableCollection<>(对于XAML,对象实例有一些限制规则)。

+0

我实现了这一点,它不起作用。 – Natrium 2009-02-03 10:28:52

+1

我建议你在你的问题中输入你的目标代码。在我的答案中有一些语法错误,我纠正它(资源,不Resouce,忘记GridView,我用手输入所有内容...)。 – belaz 2009-02-03 10:41:34

8

您可以设置DataTemplate,WPF完成所有工作。将ItemsSource设置为Bar项目的列表,然后为Bar项目定义一个DataTemplate。

<ListBox ItemsSource="{Binding Path=Foo.Bars}"> 
    <ListBox.Resources> 
     <DataTemplate DataType="{x:Type Bar}"> 
      <Label Content="hello stackoverflow" /> 
     </DataTemplate> 
    </ListBox.Resources> 
</ListBox> 

你也可以直接使用<ListBox.ItemTemplate>代替<ListBox.Resources>

Data Binding Overview在MSDN设置ItemsTemplate。

相关问题