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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 23:53:22  来源:igfitidea点击:

Bind List to DataGrid

wpfbindingdatagrid

提问by chrismasters

I have a problem binding a Listto a DataGridin 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 arrSomeInfocontains multiple items of structure SomeInfo.

arrSomeInfo包含结构的多个项目SomeInfo

The DataGridLooks 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 arrSomeInfobut 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 structis not an appropiate type for the data you're trying to represent.

WPF 不支持绑定到字段。只有属性。并且 astruct不是您要表示的数据的合适类型。