将数据网格控件绑定到Linq到实体查询结果

时间:2012-03-06 16:38:31

标签: wpf entity-framework wpfdatagrid

我是WPF和实体框架的新手。在我的应用程序中,我想做一些非常简单的事情,显示以下linq的结果来查询数据网格中的结果。 这是我的查询

C#

private void applyButton_Click(object sender, RoutedEventArgs e)
    {
        string classFilter = classNameTextBox.Text;
        var result = from c in partNumberContext.PartClasses
                     where c.chrPCName == classFilter                         
                     select c;            

    }

这是我的XML

<Window x:Class="Engenious.PartNumbers.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Part Details" Height="377" Width="607" Loaded="Window_Loaded">
<Window.Resources>
    <CollectionViewSource x:Key="PartClassSource" />
</Window.Resources>

<Grid Height="346" Width="590">

    <Label Content="Class Filter" Height="27" HorizontalAlignment="Left" Margin="75,26,0,0" Name="label1" VerticalAlignment="Top" Width="75" />
    <TextBox Height="23" HorizontalAlignment="Right" Margin="0,28,141,0" Name="classNameTextBox" VerticalAlignment="Top" Width="194" />
    <Button Content="Apply" Height="23" HorizontalAlignment="Right" Margin="0,27,26,0" Name="applyButton" VerticalAlignment="Top" Width="75" Click="applyButton_Click" />
    <DataGrid AutoGenerateColumns="False" Height="263" HorizontalAlignment="Left" Margin="53,71,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="479"  />
</Grid>

1 个答案:

答案 0 :(得分:0)

将datagrid中的AutoGenerateColumns设置为true。

以下是代码:

<Window x:Class="Engenious.PartNumbers.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Part Details" Height="377" Width="607" Loaded="Window_Loaded">
<Window.Resources>
    <CollectionViewSource x:Key="PartClassSource" />
</Window.Resources>

<Grid Height="346" Width="590">

    <Label Content="Class Filter" Height="27" HorizontalAlignment="Left" Margin="75,26,0,0" Name="label1" VerticalAlignment="Top" Width="75" />
    <TextBox Height="23" HorizontalAlignment="Right" Margin="0,28,141,0" Name="classNameTextBox" VerticalAlignment="Top" Width="194" />
    <Button Content="Apply" Height="23" HorizontalAlignment="Right" Margin="0,27,26,0" Name="applyButton" VerticalAlignment="Top" Width="75" Click="applyButton_Click" />
    <DataGrid AutoGenerateColumns="true" Height="263" HorizontalAlignment="Left" Margin="53,71,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="479"  />
</Grid>