简体   繁体   中英

Bind entities to datagrid in wpf

In winform, I do this :

    using (vbdadvertisementEntities context = new vbdadvertisementEntities())
    {
        var q = context.customers;
        customerBindingSource.DataSource = q;
        dataGridView.DataSource = customerBindingSource;
    }

Then I tried this in wpf but the datagrid just display blank :

    CollectionViewSource customerViewSource = (CollectionViewSource) FindResource("customerViewSource");
    using (vbdadvertisementEntities context = new vbdadvertisementEntities())
    {
        var q = context.customers;
        customerViewSource.Source = q;
    }

XAML :

<Window x:Class="VBDAdvertisement.WCustomerMain"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WCustomerMain" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Height="379" Width="654" xmlns:my="clr-namespace:VBDAdvertisement" Loaded="Window_Loaded">
    <Window.Resources>
        <CollectionViewSource x:Key="customerViewSource"/>
    </Window.Resources>
    <Grid DataContext="{StaticResource customerViewSource}">
        <Grid.RowDefinitions>
            <RowDefinition Height="56*" />
            <RowDefinition Height="284*" />
        </Grid.RowDefinitions>
        <DataGrid AutoGenerateColumns="False" Grid.Row="1" Name="MainDataGrid" DataContext="{Binding}" />
    </Grid>
</Window>

You have to specify the ItemsSource, specifying DataContext would just provide a context for data bindings.

Like,

<DataGrid AutoGenerateColumns="False" Grid.Row="1" Name="MainDataGrid" ItemsSource="{Binding}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM