Rownumber in Silverlight Datagrid or Listbox

My next sample uses a converter to show a line number within a datalist. I am not really satisfied with the solution, perhaps I will find in future a better way. But the concept is quite interesting and it works.

image

First we need a TextBlock to display the row number. The content is controlled by databinding. Unique data (here [daten]) is needed as parameter for later converting. 

<ListBox x:Name="lstFields" SelectionChanged="lstFields_SelectionChanged"   
Height="60" VerticalAlignment="Top"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" x:Name="stack1"> <TextBlock Text="{Binding daten,
Converter={StaticResource rownumberconverter} }"
></TextBlock> The converter needs to be declared as resource.
xmlns:c="clr-namespace:SilverlightApplication1test">
    <UserControl.Resources>
        <c:rowNumberConverter x:Key="rownumberconverter"></c:rowNumberConverter>
    </UserControl.Resources>

The converter is implemented as class which uses a special interface. The trick is to get a reference to the original data. As you can see I get a reference to application.current and cast it to the class, which is named page17. Page17 is the xaml page. There I can find my listbox named lstfields and get all items. The items are from type listboxdaten and have a property [daten]. If you compare the property with the value from the converter you get the index of the datarow.

Public Class rowNumberConverter
    Implements IValueConverter
    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type,
 ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object 
Implements System.Windows.Data.IValueConverter.Convert
        Dim mypage As page17 = CType(CType(Application.Current, App).RootVisual, page17)
        For i = 0 To mypage.lstFields.Items.Count - 1
            If CType(mypage.lstFields.Items(i), Listboxdaten).daten = value Then
                Return i + 1
            End If
        Next
        Return "nan" 'should never happen
    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, 
ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object 
Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New NotImplementedException()
    End Function
End Class

4 Comments

Comments have been disabled for this content.