wpf 将列表绑定到 DataGrid
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18068413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bind List to DataGrid
提问by chrismasters
I have a problem binding a List
to a DataGrid
in WPF. Let me explain what I have tried.
我在 WPF 中将a 绑定List
到 a 时遇到问题DataGrid
。让我解释一下我的尝试。
public struct SomeInfo
{
public string Name;
public string Description;
public string ID;
}
List<SomeInfo> arrSomeInfo;
The arrSomeInfo
contains multiple items of structure SomeInfo
.
在arrSomeInfo
包含结构的多个项目SomeInfo
。
The DataGrid
Looks something like:
本DataGrid
看起来是这样的:
<DataGrid Name="grdMailbag" AutoGenerateColumns="False" ItemsSource="{Binding}">
<DataGrid.Columns>
<DataGridTextColumn x:Name="cID" Binding="{Binding ID}" Header="ID" />
<DataGridTextColumn x:Name="cName" Binding="{Binding Name}" Header="Name" />
<DataGridTextColumn x:Name="cDescription" Binding="{Binding Description}" Header="Description" />
</DataGrid.Columns>
</DataGrid>
I have tried the following without success:
我尝试了以下但没有成功:
this.grdMailbag.ItemsSource = arrSomeInfo; //Didn't worked
this.grdMailbag.DataContext= arrSomeInfo; // Didn't worked
What is happening is that it is adding the rows as per List arrSomeInfo
but all the rows are blank.
发生的事情是它正在添加行,List arrSomeInfo
但所有行都是空白的。
回答by Federico Berasategui
Change this:
改变这个:
public struct SomeInfo
{
public string Name;
public string Description;
public string ID;
}
to this:
对此:
public class SomeInfo
{
public string Name {get;set;}
public string Description {get;set;}
public string ID {get;set;}
}
WPF does not support binding to fields. Only properties. And a struct
is not an appropiate type for the data you're trying to represent.
WPF 不支持绑定到字段。只有属性。并且 astruct
不是您要表示的数据的合适类型。