绑定ObservableCollection索引

时间:2014-02-09 13:30:48

标签: c# xaml windows-phone

我使用json web服务器检索数据并将其放入ObservableCollection我将其绑定到我的xaml中,所以我想显示像

这样的索引
  1. XXXX
  2. XXXXXXX
  3. 我怎么能得到1号,2号等等?

2 个答案:

答案 0 :(得分:2)

如果您使用的是DataGrid,那么在这种情况下您需要启用DisplayRowNumber属性,并且在DataGrid的LoadingRow事件中,您可以使用index属性设置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解决方案。在此用户中创建索引字段并使用ListBox绑定它。

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

您也可以查看Hannes博文。他正在展示Silverlight的示例,但它也适用于WPF。

答案 1 :(得分: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();
    }
}
相关问题