WPF DataGrid 绑定(bind)到 string.Length 而不是字符串文本

标签 wpf vb.net binding datagrid

我是 WPF 的新手,我真的想自己尽可能多地弄清楚......

我已经创建了我的第一个 DataGrid 控件,并尝试使用如下字符串列表填充它:

<UserControl x:Class="DataGridTest"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid Style="{StaticResource ContentRoot}">
        <DataGrid Name="MyDataGrid" ItemsSource="{Binding}" HorizontalAlignment="Stretch" Height="500"/>
    </Grid>
</UserControl>

Private Sub DataGridTest_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
        Dim StringCollection As List(Of String) = New List(Of String)
        StringCollection.Add("Test")
        StringCollection.Add("Test1")
        StringCollection.Add("Test2")
        StringCollection.Add("Test3")
        StringCollection.Add("Test4")
        MyDataGrid.DataContext = StringCollection

    End Sub

但是,它实际上填充了标题“长度”和值作为字符串的长度。为什么它本身不填充字符串值?

很明显,我在这里遗漏了一些基本的东西,但我一生都无法弄清楚它是什么。

提前致谢!

最佳答案

因为DataGrid默认情况下,自动从给定的项目类生成列,因此它将在 String 中搜索属性它可以转换为列的类。您可以通过创建自己的列并关闭 AutoGenerateColumns 来避免这种情况。

<DataGrid Name="MyDataGrid" ItemsSource="{Binding}" ... AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding}" Header="Something"/>
    </DataGrid.Columns>
</DataGrid>

关于WPF DataGrid 绑定(bind)到 string.Length 而不是字符串文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25556613/

相关文章:

WPF:删除动画后防止触发 "Completed"事件

vb.net - 如何在数据模板中设置组合框的 selectedvalue 和 itemssource

asp.net - 使用用户控件中的函数(razor 语法)

visual-studio-code - VSCode 命令面板(Ctrl + Shift + P)键盘快捷键在新安装中不起作用

c# - 双向绑定(bind)到数据集 - 更新数据库?

python - tkinter:将鼠标滚轮绑定(bind)到滚动条

c# - 如果检查了 2 个或更多值,为什么我只有一个值存储在集合中?

c# - 带有选项卡项的用户控件不显示

wpf - 如何为使用 WPF StreamGeometry 绘制的折线启用抗锯齿?

c# - 使用多线程进行慢速 Ms 互操作