【问题标题】:Formatting A Dynamically Bound Datagrid's TextColumn格式化动态绑定的 Datagrid 的 TextColumn
【发布时间】:2013-08-25 13:15:47
【问题描述】:

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

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

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

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

【问题讨论】:

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


    【解决方案1】:

    使它成为类型(我猜是用户)的只读属性(只有 getter)并绑定到它。让它变得更容易。

    【讨论】:

    • 所以一个单独的只读属性并简单地返回我的函数......我会尝试
    • 也就是说,返回通常从函数返回的内容 - 即 Left(Username, 5);不确定确切的 VB 语法,我离开 VB 已经有一段时间了:)
    • 没有骰子...我想我应该声明 StronglyTyped IList 是自动生成的。我会在上面贴出来。
    • 好的,我的意思是将属性添加到列表中的项目类型;它将类似于 ShortUsername,您将在 XAML 中绑定到它,而不是直接在用户名上。你试过了吗?
    猜你喜欢
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多