格式化动态绑定的Datagrid的TextColumn

时间:2013-08-22 17:03:26

标签: .net wpf vb.net wpfdatagrid .net-4.5

如何将数据网格中绑定列中显示的文本格式化为函数的输出?

假设我在代码隐藏中有这样的函数:

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

和数据网格一样:

    <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>

哪个绑定到StronglyTyped IList。 (这只是一个循环的SqlCeDataReader对象,可以添加到强类型列表中):

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

如何使用上面的Username函数格式化Test列?

1 个答案:

答案 0 :(得分:2)

使其成为类型上的只读属性(仅使用getter)(用户I&#39;猜测)并将其绑定到该属性。使它变得更容易。