0% found this document useful (0 votes)
6 views

3.1_DataBinding.pptx

Uploaded by

marwanelgammal55
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

3.1_DataBinding.pptx

Uploaded by

marwanelgammal55
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

C# Data Binding

Desktop Application
Learning Outcomes

01 02 03
Create the UI for Style controls Basic data binding
ExpenseReportPage concepts

04 05 06
Binding DataGrid Connect SQL Server Database
to WPF Application
01
Create the UI for
ExpenseReportPage
3. Create the UI for ExpenseReportPage
➢ ExpenseReportPage.xaml displays the
expense report for the person that's
selected on the ExpenseItHome page.
➢ Let’s create the UI for ExpenseReportPage.

Open ExpenseReportPage.xaml to
add XAML lines between the Grid
tags.
ExpenseReportPage.xaml
Make watermark.png a
The opening grid’s background using
object of Grid ImageBrush
element.

Devid the Grid into 2


columns and 2 rows.

Add Label in the second column


(indx = 1) and first row (index = 0)
with content “Expense Report For:”
ExpenseReportPage.xaml After the Label in second
grid’s column (indx = 1) and
second grid’s row (indx = 1),
Add Grid layout with 2
columns and 3 rows.
[Nesting of layout] Columns

Rows
ExpenseReportPage.xaml

Add two StackPanal in the last Grid [Nesting of layout]:


1) First one is in column index 0 and row index 0 and
has two children of Labels:
● First one with content “Name:”
● Second one has no content
2) Second one is in column index 0 and row index 1
and has two children of Labels:
● First one with content “Department:”
● Second one has no content

The StackPanel element is used to stack child


elements horizontally or vertically.
ExpenseReportPage.xaml

After the StackPanal element in the same


Grid, Add a new Grid in in column index 0
and row index 2.
This Grid has DataGrid element to add
the expense report data in it.

This is the result of


DataGrid and its style for
now, but we will talk about
DataGrid in details later.
02
Style controls
4. Style controls
➢ We want to make appearances reusable across
multiple elements.
➢ To do this we will use styles in UI.
➢ The reusability of styles helps to simplify XAML
creation and management.
➢ We will implement styles on ExpenseIt project.
➢ Implementing styles starts with open App.xaml
file.
Styles in App.xaml:

➢ As we see in the image


each control has a style.
➢ All styles added between
Application.Resources
tags.
➢ We added styles their
because resources
defined at the application
level can be accessed by
all other pages that are
part of the application.
➢ Let’s understand how to
write styles for controls.
Style controls:
When we use x:Key only elements that explicitly
reference the style will have the style applied to them.

We use Setter statements to set a property value within a Style or


a VisualState.
When used in a Style, the property that needs to be modified can
be specified directly.
Style controls:
If you create a style with a
TargetType property and base it
on another style that also
defines a TargetType property,
the target type of the derived
style must be the same as or be
derived from the target type of
the base style.
Style controls:

Here we not specify a TargetType,


then we must:
● Specify an x:Key for our Style.
● Qualify the properties in our
style with a class name (like:
Lable.VerticalAlignment).
Style controls: In ExpenseItHome.xaml we will
replace the inline styles we did
before with styles using
StaticResource and the key of our
style resource.

StaticResources are resolved at


compile time. Use StaticResources
when it's clear that you don't need
your resource re-evaluated when
fetching it (This is our case), static
resources perform better than
dynamic resources.
Style controls: In ExpenseReportPage.xaml
we will do the same thing.
03
Basic data binding
concepts
1. Basic data binding concepts
Data binding is
essentially the bridge
between your binding
target and your binding
source.

Typically, each binding has four components:


● A binding target object.
● A target property.
● A binding source.
● A path to the value in the binding source to use.
Example :
If you want to bind the content of a TextBox to the Employee.Name property, your target object
is the TextBox, the target property is the Text property, the value to use is Name, and the source
object is the Employee object.

TextBox
Employee

Employee.Name
Text
Notes:
➢ The target property must be a dependency property. Most UIElement properties are
dependency properties, and most dependency properties, except read-only ones, support
data binding by default. (Only types derived from DependencyObject can define
dependency properties; and all UIElement types derive from DependencyObject.)

➢ A Dependency Property is a property whose value depends on the external sources, such
as animation, data binding, styles, or visual tree inheritance. Not only this, but a
Dependency Property also has the built-in feature of providing notification when the
property has changed, data binding and styling.

➢ It should be noted that the binding source object is not restricted to being a custom .NET
object. WPF data binding supports data in the form of .NET objects and XML. To provide
some examples, your binding source may be a UIElement, any list object, an ADO.NET or
Web Services object, or an XmlNode that contains your XML data.
04
Binding
2. Binding
Grid layout control
We want to create a form and connect data to controls

TextBox
Label
controls
controls
Let’s see how to implement the previous form:

First: In XAML file we will


make a grid with 2
columns and 5 rows.

Second: In XAML file we will add 5 labels in each row


at first column (column index=0).

Third: In XAML file we will


add 5 TextBoxes in each
row at second column
(column index=1), Then
add data into Text.
Now let’s make a source of data to use binding:

In xaml.cs file (code-behind) we will make


class Person to add the data that we want
to bind.
This class will be out of MainWindow class.
constructor

Define
properties in
class to initialize
data into
MainWindow
class
Now let’s make a source of data to use binding:

Partial class is a class


split into two files, one
It’s actually a method of them defined in C#
call to the partial class file and the other
of the control (rather defined in XAML.
than a call up the
object hierarchy as I
first expected) _person is
should be a
source object
that equals new
instance of the
DataContext is the Person class
property that we can use to
specify the source of the
data when we are trying to Every element or class in WPF that inherit
perform data binding. from the framework element contains a
property called DataContext
Notes:
➢ The dataContext of Window at XAML file is set to Person because of MainWindow is a
partial class, one part is in C# file and the other is in XAML file.

➢ Now we can bind the data in XAML file using Binding property.
Bind data to controls:
Run the project

Data binded successfully


The Mode of Binding

➢ The default of mode binding is TwoWay.


➢ TwoWay binding means if we had to make changes in UI, then those changes would
reflect in code-behind.
➢ We want to ensure if the default binding mode in TextBox control is TwoWay and we want
to try the OneWay binding mode.
➢ We will edit our code later, but now let’s know the direction of the data flow.
Direction of the data flow

➢ OneWay binding causes changes to the source property to automatically update the
target property, but changes to the target property are not propagated back to the source
property.
➢ TwoWay binding causes changes to either the source property or the target property to
automatically update the other.
➢ OneWayToSource is the reverse of OneWay binding; it updates the source property when
the target property changes. One example scenario is if you only need to reevaluate the
source value from the UI.
TwoWay Binding Mode:

Add Click event


handler to check if
TwoWay mode is the
default mode

Add Button
control in last
Grid row
The event handler:

➢ In the code-behind we will use


MessageBox to shaw the
FirstName.
➢ The purpose of this event handler is
to show the current data in the
TextBox (which is binded) to check
if the TwoWay mode work or not.
➢ From MessageBox we will choose
Show function, but we face a
problem which we couldn’t specify
the FirstName text because the
_person object is defined within the
constructor.
➢ We should define the _person object
globally to access its properties.
We will specify the text that
we want to show
(FirstName) using string
interpolation

The $ character identifies a string literal as an interpolated string.


An interpolated string is a string literal that might contain
interpolation expressions. When an interpolated string is resolved
to a result string, items with interpolation expressions are
replaced by the string representations of the expression results.
Run the project

1 2

Change First
The message box Name to “Ahmed”
appears with the 3 then press Show
new TextBox data. button.

The binding mode is TwoWay


OneWay binding mode:

If we use OneWay
binding mode the
data will not
change.
Let’s complete our Mission !!!
Login page

User Name:

Individually build with your teammate Password:


the following task:
Login

● Add Databinding to your task.


● Make login button navigate to profile
page with data of user . welcome ,Username…

User name:
Age:
phone:
Address:
Edit Back
05
DataGrid
5. DataGrid
➢ The DataGrid control enables you to display and edit data from many different sources,
such as from a SQL database, LINQ query, or any other bindable data source.
➢ The ItemSource property of DataGrid is the key to data binding. You can bind any data
source that implements IEnuemerable. Each row in the DataGrid is bound to an object in
the data source and each column in the DataGrid is bound to a property of the data
source objects.
➢ Let’s take an example which creates a collection of objects and bind it to a DataGrid
control.

● LINQ query: Language-Integrated Query (LINQ) is the name for a set of technologies
based on the integration of query capabilities directly into the C# language. Traditionally,
queries against data are expressed as simple strings.
● IEnuemerable: It’s an interface that helps in iteration of a list collection or any kind of
collection.
DataGrid example:

Add the DataGrid


control in xaml file and
give it a Name
DataGrid example:

First, we are going to add a class to the


project. The Author class looks like
Listing 2 that has ID, Name, DOB,
BookTitle, and IsMVP members.
DataGrid example:

Now let's create a collection of


Author objects by using the List
class. The LoadCollectionData
method in Listing 3 creates a List
of Author objects.
DataGrid example:

Now the last step is to set ItemsSource


property of DataGrid. The following code
snippet sets the ItemsSource property of a
DataGrid to List of Authors.

The data loaded in


DataGrid looks like this,
which shows the properties
of the Author class a
column names.
06
Connect SQL Server
Database to WPF
Application
6. Connect SQL Server Database
to WPF Application In ExpenseIt project

Click on Tools
menu

Select Connect
to Database
Add your local server
name.
Select a database
You can get it from SQL
that you want to
Server Management
connect with.
Studio
Here we will choose
expense database.
A message box will
appear if the
connection is
succeeded or not

After choosing a
database click on Test
Connection button to
check if database is
connected
Click OK if you
ensure the database
is connected
Click on Tools
menu

Select SQL Add New


Server Query
Add your local
Server Name

Then click on
Connect
We can select the
database from
To execute this list box
the query

Write SQL
query here
● Now we can execute any
SQL query in VS.
● That helps us to see all
database changes.

The
expense_report
table
➢ In ExpenseIt page, when we
select a name and click on View
button, then should appears to us
the ExpenseReport page that
shows the expense data of the
selected name.
➢ To show the expense data of the
name that was selected in
ExpenseIt page, we should pass
that name to ExpenseReport
page at first.
➢ Let’s see how to do this…
Open
ExpenseItHome.xaml.cs

In Button_Click event
handler of View button

The parameter is the name that selected from


ListBox:
In this line we define an
● peopleListBox: The name of ListBox
object with type
element.
ExpenseReportPage and
In this line the ExpenseIt ● SelectedItem: Refers to the item
we pass to it a parameter.
page navigates selected in ListBox.
ExpenseReport page with ● selectedEmp: Now this variable is
expenseReportPage assigned with the selected listbox item
object. object after casting, so we can get its
content (the employee name).
Open
ExpenseReportPage.xaml.cs

The last step will make an error while we pass


the employee name to a parameterless
constructor to solve this problem:
● The constructor of ExpenseReportPage Now run the
should take a string parameter project then select
name and click on
View

The output is a
just a name as
we wanted
Open
Bind data from database to controls ExpenseReportPage.xaml

First: we need to know which


controls need to bind

Bind this label


with Name

Bind this label


with Department

Bind DataGrid with column


ExpenseType and Amount
Bind data from database to controls Open
ExpenseReportPage.xaml
Second: add name to these
controls
Bind data from database to controls Open
ExpenseReportPage.xaml.cs

Third: bind controls with Binding label with


database from code-behind the employee
name using the
label object name

● Create ShowTheReport()
function and call it in
constructor.
● This function should has
database connection and
display the data that we want
from database in controls
In Data Source Open
Bind data from database to controls ExpenseReportPage.xaml.cs
add the local
server name

Integrated Security
will be true if you
In Database(or Initial don’t add a password
Catalog) add the for database.
database name

Now we have the SQL connection


after writing this line.
Bind data from database to controls Open
ExpenseReportPage.xaml.cs

CommandText
property assigned
with the query cmd object of
string. SqlCommand class
to pass our
command,

conn.Open() to
open the SQL
connection and
write the query. In the query we want to select all
report when Name = @empName
The variable empName assigned in
the next line with name (we get this
name from ExpenseIt page) by
cmd.Parameters.AddWithValue()
If we want to use variable in SQL query method.
then it should start with ‘@’ sign
Bind data from database to controls Open
ExpenseReportPage.xaml.cs

From the The ExecuteReader() method


retrieving result within the SqlCommand Object
select the plays a key role in executing SQL
Department statements and retrieving query
column and bind results from the connected Data
it with label Source.
control.
Bind data from database to controls Open
ExpenseReportPage.xaml.cs

SqlDataAdapter
represents a set of data
commands and a
database connection that
are used to fill the
Create a DataSet and update a
DataTable and fill SQL Server database.
it by the
SqlDataAdapter
object Now bind with control by
setting the ItemsSource
property of a DataGrid to
the table of data.
ExpenseReportPage.xaml.cs
Output…

IMAGE
Output…

IMAGE
THANK YOU!

You might also like