2014-01-15 88 views
2

我的XAML代码将在WPF window中创建标签。如何让每个Label的内容包含从ItemSource呈现的位置?获取当前绑定索引

目前,其结果是:AAABBBCC(他们是3个标签)

我要的是:123(他们是3 label也许012,因为0指数基地)

<ItemsControl Name="m_Header"> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
     <StackPanel Orientation="Horizontal"/> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
     <Label Margin="-2,0,0,0" 
       Width="{Binding Path=Columns[0].ActualWidth, ElementName=m_DataGrid}" 
       Content="{Binding}" FontSize="15" Foreground="#777" /> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 
+1

看起来你正在试图创建一个DataGrid标题。请注意有一个[DataGridColumn.Header](http://msdn.microsoft.com/en-us/library/system.windows.controls.datagridcolumn.header.aspx)属性, – Clemens

回答

1

ItemsControl类中没有定义Index属性,所以没有显示价值的方式。然而,有一个技巧,你可以用它来得到你想要的。如果您ItemsControl.AlternationCount属性设置为一个适当的高数,那么你可以使用ItemsControl.AlternationIndex财产做同样的事情你:

<ItemsControl AlternationCount="999"><!--Set this as high as you need--> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
     <StackPanel Orientation="Horizontal"/> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
     <Label Margin="-2,0,0,0" Width="{Binding Path=Columns[0].ActualWidth, 
ElementName=m_DataGrid}" Content="{(ItemsControl.AlternationIndex), RelativeSource={ 
RelativeSource TemplatedParent}}" FontSize="15" Foreground="#777" /> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

如果你想要的数字,在不同数量的开始,你可以添加Converter只需加上或减去每个数字的相关值。

+0

它的工作:)非常感谢 –

0

添加到@sheridan答案。

根据您的底层数据源,你也许可以使用源计数属性设置AlternationCount

型号

public class DemoViewModel { 
    public ObservableCollection<string> Products { get; set; } 
    } 

设置的DataContext

public MainWindow() { 
     InitializeComponent(); 

     var vm = new DemoViewModel(); 
     vm.Products = new ObservableCollection<string> { "elm", "oak", "pine" }; 
     this.DataContext = vm; 
    } 

XAML

<ItemsControl AlternationCount="{Binding Products.Count}" 
       ItemsSource='{Binding Products}'> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
     <StackPanel Orientation="Horizontal" /> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
     <StackPanel Orientation='Vertical'> 
      <Label Margin="2" Width='200' 
       Content="{Binding (ItemsControl.AlternationIndex), RelativeSource={ 
RelativeSource TemplatedParent}}" 
       Foreground="#777" /> 
      <TextBlock Text='{Binding}' /> 
     </StackPanel> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
    </ItemsControl> 

结果

enter image description here

+0

It work :)非常感谢 –

0

所有上面的代码工作的高度:)。

如何改变Binding Path=Columns[0]Binding Path=Columns[index_here]

它在Width="{Binding Path=Columns[0].ActualWidth, ElementName=m_DataGrid}"