【问题标题】:WPF DataGrid binds to string.Length instead of string textWPF DataGrid 绑定到 string.Length 而不是字符串文本
【发布时间】:2014-10-22 18:38:54
【问题描述】:

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

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

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

提前致谢!

【问题讨论】:

    标签: wpf vb.net binding datagrid


    【解决方案1】:

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

    来避免这种情况
    <DataGrid Name="MyDataGrid" ItemsSource="{Binding}" ... AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding}" Header="Something"/>
        </DataGrid.Columns>
    </DataGrid>
    

    【讨论】:

    • 或者只对一列字符串使用ListBox - 除非您需要标题或特殊内容。
    • @lc。或使用ListBox,但不清楚OP是否想要编辑项目,因为如果你需要ItemTemplate或简单的DisplayMemberPath就足够了,也不清楚OP是否需要列标题。
    • 谢谢,这很有意义。我正在使用上面的代码进行学习练习 - 最终控件将用于编辑。
    猜你喜欢
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 2011-03-27
    相关资源
    最近更新 更多