2014-01-15 93 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}"