2014-02-09 36 views

回答

2

如果您正在使用DataGrid那麼在這種情況下,您需要啓用DisplayRowNumber財產,並在LoadingRow事件的DataGrid,您可以設置Row.Header與索引屬性。代碼可以像

<DataGrid Name="dataGrid" LoadingRow="OnLoadingRow" behaviors:DataGridBehavior.DisplayRowNumber="True" ItemsSource="{Your Binding}" /> 

void OnLoadingRow(object sender, DataGridRowEventArgs e) 
{ 
    e.Row.Header = (e.Row.GetIndex() + 1).ToString(); 
} 

編輯:正如你想這個對於ListBox,所以我建議你請this解決方案。在這個用戶正在創建索引字段並綁定與列表框。

Index = myCollection.ToList().IndexOf(e) 

你也可以檢查Hannes博客文章以及。他正在展示Silverlight的示例,但它也將與WPF一起工作。

+0

沒有,我想在我的列表框中使用它,也爲我的地圖圖釘 – user2303963

+0

我已經更新我的答案。請檢查 –

0

您可以使用IMultiValueConverter這將返回索引。

XAML

<ListBox x:Name="listBox" ItemsSource="{Binding YourCollection}"> 
    <ListBox.Resources> 
    <local:RowIndexConverter x:Key="RowIndexConverter"/> 
    </ListBox.Resources> 
    <ListBox.ItemTemplate> 
    <DataTemplate> 
     <TextBlock> 
     <TextBlock.Text> 
      <MultiBinding Converter="{StaticResource RowIndexConverter}"> 
       <Binding/> 
       <Binding ElementName="listBox" Path="ItemsSource"/> 
      </MultiBinding> 
     </TextBlock.Text> 
     </TextBlock> 
    </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

轉換

public class RowIndexConverter : IMultiValueConverter 
{ 
    public object Convert(object[] values, Type targetType, object parameter, 
          System.Globalization.CultureInfo culture) 
    { 
     IList list = (IList)values[1]; 
     return list.IndexOf(values[0]).ToString(); 
    } 

    public object[] ConvertBack(object value, Type[] targetTypes, 
           object parameter, 
           System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 
+0

對不起,但我不明白這部分{Binding RelativeSource = {RelativeSource Mode = FindAncestor, AncestorType = ListBoxItem} – user2303963

+0

我們需要通過轉換器ListBoxItem,以便我們可以在ListBox中找到它的索引。 ListBoxItem是TextBlock的可視父項,所以通過使用RealtiveSource,我們告訴綁定引擎向上遊覽可視化樹以獲取父級ListBoxItem並將其傳遞給轉換器。閱讀更多關於它[這裏](http://msdn.microsoft.com/en-us/library/ms743599(v = vs.110).aspx)。 –

+0

但我得到的錯誤屬性不存在 – user2303963

相關問題