wpf 使用 Linq 查询填充 Datagrid
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11958970/
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
Populate a Datagrid with a Linq query
提问by NomenNescio
I have the following datagrid in a wpf form:
我有以下 wpf 形式的数据网格:
<DataGrid Name="DataGrid" AutoGenerateColumns="False" VerticalScrollBarVisibility="Auto">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Width="200"></DataGridTextColumn>
<DataGridTextColumn Header="Text" Width="200"></DataGridTextColumn>
<DataGridTemplateColumn Header="Edit" Width="50">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button>View Details</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
And I'd like to populate it from my code. I use a linq statement to get the values I'd like to put in the datagrid
我想从我的代码中填充它。我使用 linq 语句来获取我想放入数据网格的值
var query =
(
from modules ...
join ...
join ...
where ...
select new { ID = modules.ID, Name = strings.Name, Text = stringTexts.Text }
);
I'd like to populate the columns 'Name' and 'Text' with Name and Text from the query, but I also want there to be a button in each row, and when that button is pressed, I have to know the ID of the row that was pressed, but the ID does not have to show up on the grid.
我想用查询中的名称和文本填充“名称”和“文本”列,但我也希望每一行都有一个按钮,当按下该按钮时,我必须知道被按下的行,但 ID 不必显示在网格上。
How do I populate the grid with these values?
如何使用这些值填充网格?
回答by Nikhil Agrawal
Tell columns to bind to a property using
告诉列绑定到属性使用
<DataGridTextColumn Header="Name" Width="200" Binding="{Binding Name}" />
and so on for other columns.
对于其他列,依此类推。
Then in code behind
然后在后面的代码中
DataGrid.ItemsSource = query;
回答by SarahK
This should work for you:
这应该适合你:
Grid.DataSource = from x in modules
select new
{
x.Name,
x.Text
};
Grid.DataBind();
Best of luck!
祝你好运!

