Freigeben über


Simple Databinding example with Entity Framework and Windows Presentation Foundation

 

A simple way to get Data Binding with WPF and Entity Framework

First create two tables for Author and Book which will be used in this example:

create table Author (AuthorId int primary key, AuthorName nvarchar(50))

create table Book (BookId int primary key, AuthorId int, Title nvarchar(50), Description nvarchar(200), Price money)

alter table Book add constraint FK_Book_Author foreign key (AuthorId) references Author (AuthorId)

insert into Author values (1, 'Gambardella, Matthew')

insert into Author values (2, 'Ralls, Kim')

insert into Author values (3, 'Corets, Eva')

insert into Book values (1, 1, 'XML Developers Guide', 'An in-depth look at creating applications with XML.', 4.95)

insert into Book values (2, 1, 'Foods of the world.', 'Simply a book about food.', 5.95)

insert into Book values (3, 1, 'Cars', 'A book about cars.', 8.95)

insert into Book values (4, 2, 'Scarecrows', 'This be could horror or agriculture.', 4.15)

insert into Book values (5, 3, 'Book of blue', 'First in a series of books about colors', 6.30)

insert into Book values (6, 3, 'EF', 'Some tips and trics on Entity Frameworks', 3.45)

Then create a new WPF application in Visual Studio.

Right click the Project and select Add -> New Item, select ADO.Net Entity Data Model.

Call it “Bookshop.edmx”, select “Generate from database”, select an existing data connection or create a new one to the database where you created the tables above.

Call the Entity connection “BookshopEntities”, select the Author and Book tables and save the model as “BookshopModel” and hit Finish.

Back to the Window. Enter this in the .xaml file to create the window that will hold two dropdowns and a textbox that will show the data.

<Window x:Class="BlogTest.MainWindow"

       xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"

       xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"

       Title="MainWindow" Height="300" Width="400">

        <Grid>

            <Grid.ColumnDefinitions>

                <ColumnDefinition Width="180" />

                <ColumnDefinition Width="*" />

            </Grid.ColumnDefinitions>

            <Grid.RowDefinitions>

                <RowDefinition Height="25" />

                <RowDefinition Height="*" />

            </Grid.RowDefinitions>

           

            <ComboBox DisplayMemberPath="AuthorName" ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="true"

                     Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="1" Name="cbAuthors" SelectionChanged="cbAuthors_SelectionChanged" />

            <ComboBox DisplayMemberPath="Title" ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="true"

                     Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="1" Name="cbBooks" SelectionChanged="cbBooks_SelectionChanged" />

            <TextBlock Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Name="tbDesc"/>

        </Grid>

</Window>

Then open the code behind window for the Windows and enter the following (obviously this is without any checks for exceptions etc. You may want to add that).

    public partial class MainWindow : Window

    {

        BookshopEntities ctx = new BookshopEntities();

        public MainWindow()

        {

            InitializeComponent();

            FillAuthors();

        }

        private void FillAuthors()

        {

            var q = from a in ctx.Author select a;

            cbAuthors.DataContext = q;

        }

        private void FillBook()

        {

            Author author = (Author)cbAuthors.SelectedItem;

            var q = from book in ctx.Book

                    orderby book.Title

                    where book.AuthorId == author.AuthorId

                    select book;

            cbBooks.DataContext = q;

        }

        private void FillDescription()

        {

            Book book = (Book)cbBooks.SelectedItem;

            tbDesc.Text = book.Description;

        }

        private void cbAuthors_SelectionChanged(object sender, SelectionChangedEventArgs e)

        {

       FillBook();

        }

        private void cbBooks_SelectionChanged(object sender, SelectionChangedEventArgs e)

        {

            FillDescription();

        }

    }

And run. This should give the Authors in left drop down.

When changing Authors, the authors books should show in the right dropdown and the description should end up in the Textbox.