无法将datagrid绑定到列表 [英] cannot bind datagrid to list

查看:62
本文介绍了无法将datagrid绑定到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在引发事件时在datagrid中显示列表的内容.参见下面的代码

I am trying to show the contents of list in datagrid when an event is raised. See the code below

List<string> mlw = new System.Collections.Generic.List<int>();<br />
mlw.Add("qwe1");<br />
mlw.Add("qwe2");<br />
mlw.Add("qwe3");<br />
mlw.Add("qwe4");<br />
mlw.Add("qwe5");<br />
dataGrid1.ItemsSource = mlw;</int></string>



我看到的结果是,我可以看到5行的空间,每个行中都写有"4".



What I see the result I can see the space for 5 rows with "4" written in each of it

推荐答案

WPF绑定的工作方式,它试图绑定到列表中对象的属性.如果未指定,则它将使用找到的第一个属性(对于字符串,这是Length属性).为了解决这个问题,我使用了LinQ和一个匿名类型,就像这样

The way WPF binding works, it tries to bind to a property of the object in the list. If one is not specified, then it will use the first property it finds (for strings this is the Length property). To get around this, I use LinQ and an anonymous type, something like this

List<string> mlw = new List<string>(){"qwe1","qwe2","qwe3","qwe4","qwe5"};
           var values = from str in mlw select new { value = str };
           dataGrid1.DataContext = values.ToList();



这将显示实际的字符串值

这是xaml声明



and this will show the actual string value

This is the xaml declaration

<DataGrid Name="dataGrid1" Grid.Row="4" ItemsSource="{Binding}" AutoGenerateColumns="True"/>



希望对您有帮助



Hope this helps


这篇关于无法将datagrid绑定到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆