Kevin
Kevin

Reputation: 2688

Formatting A Dynamically Bound Datagrid's TextColumn

How can I format the text displayed in a bound column in my datagrid to the output of a function?

Say I have a function like this in my code-behind:

Function Test(ByVal str As String) As String
    Return Left(str, 5)
End Function

And a datagrid like:

    <DataGrid Name="dg_Users" IsReadOnly="True" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="User ID" Binding="{Binding UserID}" />
            <DataGridTextColumn Header="Username" Binding="{Binding Username}" />
        </DataGrid.Columns>
    </DataGrid>

Which is bound to a StronglyTyped IList. (which is simply a SqlCeDataReader object looped through to add to a strongly typed list):

Private Shared Function Map(Of T As New)(ByVal _Rdr As IDataReader) As IList(Of T)
    Try
        Dim _t As Type = GetType(T)
        Dim _en As New List(Of T)()
        Dim _ht As New Hashtable()
        Dim _props As PropertyInfo() = _t.GetProperties()
        Parallel.ForEach(_props, Sub(info)
                                     _ht(info.Name.ToUpper()) = info
                                 End Sub)
        While _Rdr.Read()
            Dim newObject As New T()
            For index As Integer = 0 To _Rdr.FieldCount - 1
                Dim info As PropertyInfo = DirectCast(_ht(_Rdr.GetName(index).ToUpper()), PropertyInfo)
                If (info IsNot Nothing) AndAlso info.CanWrite Then
                    info.SetValue(newObject, IsNull(Of Object)(_Rdr.GetValue(index), Nothing), Nothing)
                End If
            Next
            _en.Add(newObject)
        End While
        _Rdr.Close()
        Return _en
        _ht.Clear() : _en.Clear()
    Catch ex As Exception
        Return Nothing
    End Try
End Function

How do I format the Username column utilizing the Test function above?

Upvotes: 0

Views: 54

Answers (1)

Alex Paven
Alex Paven

Reputation: 5549

Make it a read-only property (with just the getter) on the type (User I'm guessing) and bind to that instead. Makes it a lot easier.

Upvotes: 2

Related Questions