WPF DataGrid绑定到string.Length而不是字符串文本 [英] WPF DataGrid binds to string.Length instead of string text
问题描述
我是WPF的新手,并且真正地在尝试自己找出尽可能多的东西...
I'm new to WPF, and am genuinely trying to figure out as much as possible by myself...
我已经创建了第一个DataGrid控件,并且尝试使用如下字符串列表填充它:
I've created my first DataGrid control, and I am trying to populate it with a list of strings as below:
<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
但是,它实际上以标题"Length"填充,并以字符串的长度作为值.为什么它本身不填充字符串值?
However, it actually populates with a heading "Length" and values as the length of the strings. Why is it not populating with the string values, themselves?
很明显,我在这里缺少一些基本的东西,但是我一生无法弄清它到底是什么.
It's clear that I'm missing something fundamental here, but I can't for the life of me figure out what it is.
提前谢谢!
推荐答案
由于默认情况下DataGrid
自动从给定的项目类生成列,因此它将在String
类中搜索可转换为列的属性.您可以通过创建自己的列并关闭AutoGenerateColumns
Because DataGrid
by default auto generates columns from given item class so it will search for properties in String
class that it can convert into column. You can avoid that by creating your own column and turning off AutoGenerateColumns
<DataGrid Name="MyDataGrid" ItemsSource="{Binding}" ... AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding}" Header="Something"/>
</DataGrid.Columns>
</DataGrid>
这篇关于WPF DataGrid绑定到string.Length而不是字符串文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!