我使用json服务器检索数据并将其放入ObservableCollection,然后将其绑定到xaml中,因此我希望显示如下所示的索引
我怎么能得到第一,第二,等等?
发布于 2014-02-09 13:43:28
如果您正在使用DataGrid,那么在这种情况下,您需要启用DisplayRowNumber属性,而在DataGrid的LoadingRow事件中,您可以使用索引属性设置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,所以我建议您检查这解决方案。在这个用户中,创建索引字段并将其与ListBox绑定。
Index = myCollection.ToList().IndexOf(e)此外,您也可以查看汉尼斯博客文章。他为Silverlight展示了榜样,但它也将与WPF一起工作。
发布于 2014-02-09 14:04:08
您可以使用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();
}
}https://stackoverflow.com/questions/21659621
复制相似问题