首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >结合ObservableCollection指数

结合ObservableCollection指数
EN

Stack Overflow用户
提问于 2014-02-09 13:30:48
回答 2查看 1.7K关注 0票数 0

我使用json服务器检索数据并将其放入ObservableCollection,然后将其绑定到xaml中,因此我希望显示如下所示的索引

  1. xxxx
  2. ×××

我怎么能得到第一,第二,等等?

EN

回答 2

Stack Overflow用户

发布于 2014-02-09 13:43:28

如果您正在使用DataGrid,那么在这种情况下,您需要启用DisplayRowNumber属性,而在DataGrid的LoadingRow事件中,您可以使用索引属性设置Row.Header。代码可能就像

代码语言:javascript
复制
<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,所以我建议您检查解决方案。在这个用户中,创建索引字段并将其与ListBox绑定。

代码语言:javascript
复制
Index = myCollection.ToList().IndexOf(e)

此外,您也可以查看汉尼斯博客文章。他为Silverlight展示了榜样,但它也将与WPF一起工作。

票数 2
EN

Stack Overflow用户

发布于 2014-02-09 14:04:08

您可以使用IMultiValueConverter来实现这一点,这将返回索引。

XAML

代码语言:javascript
复制
<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>

变换器

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21659621

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档